简体   繁体   English

如何使用Mongodb和Node JS在多个Collection中保存数据

[英]How to Save data in multiple Collection using Mongodb and node js

I am using nodeJS and mongodb in one of my project. 我在我的项目之一中使用nodeJS和mongodb。

I am trying to save data in multiple collection in one save button. 我试图在一个保存按钮中将数据保存在多个集合中。

The code which I am using to achieve this is as follow: 我用来实现此目的的代码如下:

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');        
                });
        }       

Could you please tell what is wrong in the above code? 你能告诉我上面代码有什么问题吗?

Thank you. 谢谢。

Regards, Saloni 问候,萨罗尼

I want to give an explanation regarding the above issue with the code. 我想对上述问题进行解释。

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');        
                });
  }  
    }); 

I think move IF block inside callback of insert login function like this should work 我认为像这样的插入登录功能的回调内部移动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');
        });
    }

});

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

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