【问题标题】:mongoose - how come findOne returns the mongoose Model object but find doesn't?mongoose - 为什么 findOne 返回 mongoose Model 对象但 find 没有?
【发布时间】:2013-01-17 00:22:47
【问题描述】:

当我使用 mongoose findOne 方法时,它发现在回调中返回的对象是一个有效的 mongoose Model 对象(这意味着我可以在其上调用 mongoose 模型帮助器方法,例如 id 用于 sub-文件或remove 删除它),当我调用猫鼬find 方法时,我只是返回一个表示我正在寻找的文档的javascript对象?

【问题讨论】:

  • 使用find,您可以返回一组模型 Mongoose Model 实例。

标签: node.js mongodb mongoose


【解决方案1】:

findOne 为您提供单个 mongoose 文档,而 find 为您提供所有匹配的 mongoose 文档的数组,而不是光标。

YourModel.find({ something: true }, function (err, docs) {
  if (err) return handleErrorSomehow(err)
  console.log(Array.isArray(docs)) // true
  docs.forEach(function (doc) {
    console.log(typeof doc.save) // function
  })
})

【讨论】:

    猜你喜欢
    • 2018-08-07
    • 2018-04-03
    • 2018-06-09
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 2019-09-11
    相关资源
    最近更新 更多