MongoDB、Mongoose:迭代查找结果

Phi*_*hil 1 mongoose mongodb node.js

MongoDB find() 让我有点困惑。它可以用作 Promise,与 exec 或回调一起使用。还有 next() 和 forEach() 方法,但这些方法似乎仅在 MongoDB shell 中可用,而在 Mongoose 中不可用(或者我可以在 Node.js/Mongoose 中创建游标吗?)。

我想要做的是迭代一个集合,而不是一次将所有 1000 多个找到的项目加载到内存中(而不是一个接一个),并为每个找到的元素调用一些 API 并更新数据库中的元素。

最直接的方法是什么?

Mat*_*att 7

通过异步迭代器进行流式传输

for await (const doc of Person.find()) {
  console.log(doc)
  doc.set('field', 'value')
  await doc.save()
}
Run Code Online (Sandbox Code Playgroud)

对于< 10.x 的节点

const cursor = Person.find().cursor()
for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
  /** set and save **/
}
Run Code Online (Sandbox Code Playgroud)