0

I am using nodeJS and mongodb in one of my project.

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

2 Answers 2

2

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');        
                });
  }  
    }); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Niraj, just one more change I did and that's work for me.
0

I think move IF block inside callback of insert login function like this should work

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

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.