Hug*_*sto 5 javascript ajax mongoose mongodb
我在数组中有2个不同的对象,我想使用这些对象更新我的mongodb中的集合所以我虽然使用这样的东西:
for (i = 0 ; i < array.length ; i++) {
Model.update({array[i]._id},{$set : {'credits_pending' : array[i].credits_pending}},false,true)
}
Run Code Online (Sandbox Code Playgroud)
但它只更新我的数组的第一个值,我的意思是数组[0]
为什么?
Mik*_*key 10
首先,Mongoose中的更新(以及大多数其他操作)是异步的,因此您需要等到操作完成后再继续.通常最好在同一个集合上一次执行一个操作.通过for循环,您在同一个集合上同时运行两个异步操作,这可能会产生不良行为.
其次,我认为你的Model.update()参数略有偏差.
我喜欢在使用Mongoose时使用async.js,所以下面是一个关于如何一次更新一个对象数组的示例.
var async = require('async');
async.eachSeries(array, function updateObject (obj, done) {
// Model.update(condition, doc, callback)
Model.update({ _id: obj._id }, { $set : { credits_pending: obj.credits_pending }}, done);
}, function allDone (err) {
// this will be called when all the updates are done or an error occurred during the iteration
});
Run Code Online (Sandbox Code Playgroud)