简体   繁体   English

在节点js中查询mongodb

[英]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. 我有一个注册按钮,它仅在数据唯一时才将数据插入mongo db集合中,否则用户应停留在同一页面上。 For implementing the same , I am doing upsert:true. 为了实现相同的目的,我正在做upsert:true。 This is my code for node js 这是我的节点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. 谢谢。

use, you need to specify $set in your update query. 使用时,您需要在更新查询中指定$ set。

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. 编辑:发送result对象,根据nModified检查result对象的n值,以获取更新和修改的记录数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM