【问题标题】:Mongoose for/await/of loop is `sort` required in Query?Mongoose for/await/of 循环在 Query 中是否需要“排序”?
【发布时间】:2021-03-04 17:02:38
【问题描述】:

在 Mongoose 的文档中有 following example 关于使用 async/await 进行迭代:

// Works without using `cursor()`
for await (const doc of Model.find([{ $sort: { name: 1 } }])) {
  console.log(doc.name);
}

由于我是 MongoDB 的新手,我想了解是否需要 [{ $sort: { name: 1 } }] 才能使查询正常工作,或者这只是一个示例。

我的目标是迭代一个集合中的所有文档,所以我想下面的代码应该没问题:

// Works without using `cursor()`
for await (const doc of Model.find()) {
  console.log(doc.name);
}

对吗?

【问题讨论】:

    标签: javascript mongodb mongoose cursor


    【解决方案1】:

    在 Mongodb 4.2 和更早版本中,将对象数组传递给 find 将触发异常。所以如果你运行:

    Model.find([{ $sort: { name: 1 } }]).then(...)
    

    你会得到:

    ObjectParameterError: Parameter "filter" to find() must be an object
    

    然而,在 MongoDB 4.4 中,[{ $sort: { name: 1 } }] 实际上可以传递给 find。但是,$sort 实际上并没有进入find 参数,而是应该像这样使用Model.find().sort({name: 1})

    这让我相信您提供的链接中的[{ $sort: { name: 1 } }] 只是一个占位符,服务器没有任何用途。这么跑

    for await (const doc of Model.find()) {
    

    完全没问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      • 2019-03-15
      • 2020-01-14
      • 2019-02-19
      • 2021-03-05
      • 2015-06-11
      • 2020-07-10
      相关资源
      最近更新 更多