如何使用Mongodb和节点js

时间:2018-03-15 10:44:44

标签: javascript node.js database mongodb express

我在我的一个项目中使用nodeJS和mongodb。

我正在尝试在一个保存按钮中保存多个集合中的数据。

我用来实现此目的的代码如下:

var lastInsertId;
loginData={
        userName: req.body.txtUsername,
        password: req.body.txtPassword,
        active:1,
        createdOn:new Date(),
        updatedOn:new Date()
    };
var dbo = db.db("test");
dbo.collection("login").insertOne(loginData, function(err, result) {
        if (err) throw err;
        lastInsertId=result.insertedId;
}); 

if(lastInsertId){
            usersData={
                email: req.body.txtEmail,
                firstName: req.body.txtFirstName,
                lastName:req.body.txtLastName,
                mobileNumber:req.body.txtMobileNumber,
                login_id:lastInsertId,
                active:1,
                createdOn:new Date(),
                updatedOn:new Date()
            };

            dbo.collection("users").insertOne(usersData, function(err, result) {
                if (err) throw err;
                console.log('saved to users');        
                });
        }       

您能否告诉我上述代码有什么问题?

谢谢。

此致 SALONI

2 个答案:

答案 0 :(得分:2)

我想用代码解释上述问题。

var lastInsertId;  //it is undefined right now



//The following function is an asynchronous function. 
var dbo = db.db("test");
dbo.collection("login").insertOne(loginData, function(err, result) {
        if (err) throw err;
        lastInsertId=result.insertedId;
}); 

/*NodeJs doesn't run synchronously. So, while it is running
above function i.e. insertOne, without it being completed it 
reaches here.
Since, the above function is not completed
executing, lastInsertId will be undefined still. 
So, the following block of code doesn't run */



     if(lastInsertId){  //this block won't run
                usersData={
                    //key-value pairs
                };

                dbo.collection("users").insertOne(usersData, function(err, result) {
                    if (err) throw err;
                    console.log('saved to users');        
                    });
      }      


    /*The solution to the above problem can be achieved by putting the 
    code block inside 'if(lastInsertId)' in callback of insert login. 
    So it would run only after the execution of insertOne function.*/ 

    //Therefore the correct code would be: 
    var dbo = db.db("test");
    dbo.collection("login").insertOne(loginData, function(err, result) {
            if (err) throw err;
            lastInsertId=result.insertedId;


           if(lastInsertId){  //this block will run
            usersData={
                //key-value pairs
            };

            dbo.collection("users").insertOne(usersData, function(err, result) {
                if (err) throw err;
                console.log('saved to users');        
                });
  }  
    }); 

答案 1 :(得分:0)

我认为在这样的插入登录函数的回调中移动IF块应该可以工作

var lastInsertId;
loginData = {
    userName: req.body.txtUsername,
    password: req.body.txtPassword,
    active: 1,
    createdOn: new Date(),
    updatedOn: new Date()
};
var dbo = db.db("test");
dbo.collection("login").insertOne(loginData, function (err, result) {
    if (err) throw err;
    lastInsertId = result.insertedId;

    if (lastInsertId) {
        usersData = {
            email: req.body.txtEmail,
            firstName: req.body.txtFirstName,
            lastName: req.body.txtLastName,
            mobileNumber: req.body.txtMobileNumber,
            login_id: lastInsertId,
            active: 1,
            createdOn: new Date(),
            updatedOn: new Date()
        };

        dbo.collection("users").insertOne(usersData, function (err, result) {
            if (err) throw err;
            console.log('saved to users');
        });
    }

});