我的程序中有一个功能,其中有一项工作将每2小时获取一次文件并解析为json,然后将这些数据添加到数据库中。
使用upsert,如果没有匹配项,我可以创建记录,然后更新匹配的记录,这没有问题。
我每2小时获取的文件具有动态值,该值取决于总数据,有时会减少某些数据,有时会添加新数据。
例如,在最初的2个小时中,文件包含3条记录,我能够向数据库中添加3条记录,而该数据库现在具有3条当前记录。
数据库中的当前记录
value: {
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
"userId": 2,
"id": 2,
"title": "delectus aut autem2",
"completed": false
},
"userId": 3,
"id": 3,
"title": "delectus aut autem3",
"completed": false
}
但是在接下来的2小时中,仅删除了文件中的2条记录。因此,由于存在匹配项,它将更新2条记录
value: {
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
"userId": 2,
"id": 2,
"title": "delectus aut autem2",
"completed": false
},
它还将更新文件中已删除但已存在于数据库集中的所有记录,即已完成== true
Userid3完成值现在等于true。
value: {
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
"userId": 2,
"id": 2,
"title": "delectus aut autem2",
"completed": false
},
"userId": 3,
"id": 3,
"title": "delectus aut autem3",
"completed": true
}
var myQuery = { 'id': value.id }
//Update existing data ang create if no data found using upsert
Person.model.findOneAndUpdate(myQuery, value, { upsert: true }, function (err, doc) {
if (err) {
console.log("[ERROR]", err)
}
})