【问题标题】:Mongoose get nested document using another fieldMongoose 使用另一个字段获取嵌套文档
【发布时间】:2021-10-05 02:04:28
【问题描述】:

假设我在集合中有一个文档

{
  _id: "3434v4vcvc254t34vtds",
  currentItemId: "v281",
  items: {
      v279: [/*Some Data*/],
      v280: [/*Some Data*/],
      v281: [/*Some Data*/]
  }
}

我需要获取当前项目。
但是我可以使用两个查询来做到这一点

let data= await schema.findById("3434v4vcvc254t34vtds", {currentItemId});
let itemId = `items.${data.currentItemId}`
let item = await schema.findByID("3434v4vcvc254t34vtds", { [itemId] })

我需要使用一个查询来获取当前项目。

【问题讨论】:

  • 你的预期输出是什么?
  • @J.F.预期输出:项目文档中的 v281 数组

标签: node.js mongoose nested


【解决方案1】:

findById 之后使用populate

const data = await schema.findById('3434v4vcvc254t34vtds').populate('currentItemId').exec()

【讨论】:

    猜你喜欢
    • 2011-11-10
    • 2021-05-15
    • 1970-01-01
    • 2011-09-01
    • 2014-08-05
    • 1970-01-01
    • 2016-04-25
    • 2017-01-29
    • 1970-01-01
    相关资源
    最近更新 更多