0

I have a sign up button which inserts data in mongo db collection only if the data is unique otherwise the user should stay on the same page. For implementing the same , I am doing upsert:true. This is my code for node js

var mongoClient=require('mongodb').MongoClient;
var url='mongodb://localhost:27017/test';
app.post('/newuser', function(req, res) {
    username=req.body.username;
    password=req.body.password;

mongoClient.connect(url,function(err,db){
    //console.log("connected")
    db.collection('users',function(err,collection){
        collection.update({username:username, password:password},{upsert:true},function(err,result){
            res.send(result.insertedCount);
        });
    })
})
});

And the code for the frontend is

$.ajax({
    type:'POST',
    url:'/newuser',
    data:{
        username:username,
        password:password
    },
    success:function(result){
        console.log(result);
        if(result===1){

        that.setState({
            isLoggedin:true
        })
    }else{
        alert("not inserted");
    }
    }
})
return false;

}

Every time I run the server, the success function doesn't get executed.What is wrong with the code? Thanks.

4
  • check the response to API in Network tools, Chrome Commented Jul 11, 2017 at 13:30
  • failed to load response data @atulquest93 Commented Jul 11, 2017 at 13:31
  • Open Console (Ctrl+Shift+J) > Network tools Now make hit .. it will show the request.. click on the request and check response is browser is receiving data or their is some error. Commented Jul 11, 2017 at 13:33
  • the response is coming as undefined @atulquest93 Commented Jul 11, 2017 at 16:22

1 Answer 1

1

use, you need to specify $set in your update query.

collection.update(
  {},
  {$set: { username, password }},
  {upsert:true},
  function(err,result){
      res.send(result);
  }

EDIT: send result object, check based on nModified, n values of result object to get the number of records updated and modified.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.