weixin_33713707 2017-07-11 13:28 采纳率: 0%
浏览 84

在节点js中查询mongodb

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.

  • 写回答

1条回答 默认 最新

  • weixin_33712881 2017-07-11 17:53
    关注

    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.

    评论

    报告相同问题?

    悬赏问题

    • ¥15 如何通过求后验分布求得样本中属于两种物种其中一种的概率?
    • ¥15 q从常量变成sin函数,怎么改写python代码?
    • ¥15 图论编程问题,有可以指导的吗
    • ¥15 DEA的CCR模型画图
    • ¥15 请假各位一个关于安卓车机的问题
    • ¥15 光谱仪怎么看这样的透射谱
    • ¥15 pyqt5 如何实现输入框输入关键词,下拉框显示模糊查询返回的结果?
    • ¥20 fluent模拟,可以燃烧和相变同时模拟吗?
    • ¥50 海康摄像头,C#如何识别车牌号码和抓取JPG
    • ¥15 yolov5 pt转engine的问题