如何使用 .forEach() 插入多个集合并检查它是否存在

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

我想使用 .forEach() 将多个用户详细信息插入到我的 Mongodb 数据库中。 在插入记录之前,我想检查用户记录是否存在。如果用户不存在则插入新的用户记录,否则更新现有的用户记录。

下面是

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

当 运行 此代码片段时,它仅检查数组中的第一个对象并插入我的数据库中。但是下次当第三个对象要执行时,它不会像新记录一样检查和插入。

我不明白发生了什么事。

请告诉我如何解决。

谢谢。

你应该做你的异步循环

参见:https://caolan.github.io/async/docs.html#eachOfSeries

示例代码

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"
}, ];

async.eachOfSeries(dataArray, function(dataVar, key, callback) {
    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');
                callback();
            })
        } else { // Update records if user exist
            User.update({
                id: dateVar.id
            }, {
                email: dataVar.email
            }, function(err, result) {
                console.log('Record Updated');;
                callback();
            });
        }
    })
}, function(err) {
    if (err) console.error(err.message);
    // configs is now a map of JSON data
    console.log("All done")
});