mongodb:cursor.each里面的collection.update在更新完成之前解析

时间:2016-07-26 10:11:45

标签: mongodb promise

首先,我使用mongodb-promise作为MongoClient的包装。

我需要从一个集合中获取所有记录" people"符合特定条件,然后更新每个条件。

为此我有这个代码来找到所有人:

return db.collection('people')

.then( (collection) => {
    // Store reference to collection for future use
    peopleCollection = collection;

    return collection.find({a:1})
})

然后调用它来更新每条记录:

.then( (people) => {

    // Process each people
    return people.each( (person) => {

        person.b = 2;

        // Where peopleCollection is a reference to my collection
        return peopleCollection.update({_id: person._id}, person)
    })
})

然后我添加另一个承诺链来获取b!= 2的所有人,我找到了很多记录,我计算了它们。但是当我重复执行这个脚本时,计数会减少,这意味着当promise已经解决时,mongo仍在更新其他记录。我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

也许:

.then( (people) => {

// Process each people
return people.each( (person) => {


    // Where peopleCollection is a reference to my collection
    return peopleCollection.update({_id: person._id}, {$set:{b:2}})
  })
})
相关问题