Wednesday, 10 May 2017

How to insert Multiple collections using .forEach() and check if it exist or not

I want to insert multiple user details using .forEach() into my Mongodb Database. Before insert records I want to check whether user record is exist or not. If user is not exist then insert new User record otherwise update the existing user record.

Below is

var dataArray=[
        {"id":"1","name":"abc","email":"abc@gmail.com"},
        {"id":"2","name":"xyz","email":"xyz@gmail.com"},
        {"id":"1","name":"abc","email":"abc@gmail.com"},
         ];

dataArray.forEach(function(dataVar){

//check record exist or not

User.findOne({id:dataVar.id},function(err,user){
    if(!user){// Insert If user not exist
        var userSchema=new User({
            id:dataVar.id,
            name:dataVar.name,
            email:dataVar.email
        });
        userSchema.save(function(err,result){
        console.log('New Record Inserted');     
        })
    }else{ // Update records if user exist
        User.update({id:dateVar.id},{email:dataVar.email},function(err,result){
        console.log('Record Updated');;     
        }); 
    }
})
});

When run this code snippet, its checking only first object from array and insert in my DB. But next time when 3rd object going to execute then its not checking and inserting like a new record.

I am not getting whats going on.

Please let me know how to solve it.

Thanks.



via Saurabh Sharma

No comments:

Post a Comment