简体   繁体   English

for或foreach循环中的Node JS Mongoose更新查询,可能吗?

[英]Node JS Mongoose update query inside for or foreach loop, is it possible?

I have 2 different objects inside an array, and i want to use those objects to update a collection in my mongodb So i though about using something like this: 我在数组中有2个不同的对象,我想使用这些对象来更新mongodb中的集合,所以我虽然要使用类似的方法:

for (i = 0 ; i < array.length ; i++) {
Model.update({array[i]._id},{$set : {'credits_pending' : array[i].credits_pending}},false,true)
}

But it only updates the first value of my array, i mean, array[0] 但是它只会更新数组的第一个值,我的意思是,数组[0]

Why? 为什么?

For one thing, update (and most other operations) in Mongoose is asynchronous so you need to wait till the operation is done before continuing. 一方面,Mongoose中的更新(和大多数其他操作)是异步的,因此您需要等到操作完成后才能继续。 It's usually better to do one operation at a time on the same collection. 通常最好一次对一个集合执行一次操作。 With the for loop, you're running two asynchronous operations at the same time on the same collection, which might give an undesired behavior. 使用for循环,您将在同一集合上同时运行两个异步操作,这可能会导致意外的行为。

Second, I think your Model.update() arguments are slightly off. 其次,我认为您的Model.update()参数略有偏离。

I like to use async.js when working with Mongoose, so below is an example on how you can update an array of objects one at a time. 我喜欢在使用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
});

I don't know how your schema looks like but if that is the only way to do that, try something like - 我不知道您的架构是什么样子,但是如果那是唯一的方式,请尝试-

//array - your original array
        async.eachSeries(array, function(rec, callback) {
             updateRecord(rec._id, rec.credits_pending)
                  .then((updated) => {
                      callback();
                    })
        }, function(err){
          //execution comes here when array is fully iterated.
        });

    function updateRecord(id, credits) {
    return Model.update({array[i]._id},{$set : {'credits_pending' : array[i].credits_pending}});
    }  

Mongoose internally supports promise so you don't have to worry about anything else. 猫鼬在内部支持承诺,因此您不必担心其他任何事情。
"Note" - For updating multiple documents you should select some property that is common to all the documents. “注释”-要更新多个文档,应选择所有文档共有的某些属性。 This approach is not correct and you should design your schema to avoid such scenarios. 这种方法是不正确的,您应该设计架构以避免此类情况。 This answer is in the case you don't have any other choice. 如果您别无选择,请回答此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM