How can I use a cursor.forEach() in MongoDB using Node.js?

前端 未结 10 788
你的背包
你的背包 2020-11-27 14:04

I have a huge collection of documents in my DB and I\'m wondering how can I run through all the documents and update them, each document with a different value.

10条回答
  •  情深已故
    2020-11-27 15:01

    And here is an example of using a Mongoose cursor async with promises:

    new Promise(function (resolve, reject) {
      collection.find(query).cursor()
        .on('data', function(doc) {
          // ...
        })
        .on('error', reject)
        .on('end', resolve);
    })
    .then(function () {
      // ...
    });
    

    Reference:

    • Mongoose cursors
    • Streams and promises

提交回复
热议问题