Aayushi
Aayushi

Reputation: 1816

Querying mongodb in node js

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.

Upvotes: 0

Views: 39

Answers (1)

Ankit Balyan
Ankit Balyan

Reputation: 1329

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.

Upvotes: 1

Related Questions