首页 > 解决方案 > 使用 mongoose.findOne 中的文档获取子文档

问题描述

首先,我的代码运行良好,但我不知道是否做对了。我有一个具有此架构的父模型单元

{
  info: {...},
  chapters: {_id: string, ...}
}

章节架构是这样的:

{
  info: {...},
  content:  string
}

现在在客户端,如果我正在编辑章节,并且想将更改放入数据库,我会这样做

Units.findOne({'chapters._id': chapter_id}) //this query will return the parent unit
.then(unit=>{ //is there a way to have the chapter with unit here??
  const chapter = unit.chapters.find(chapter=> chapter._id === chapter_id)
 //seems like duplicated. i already found the unit based on the chapter_id
  //after that i update the chapter
})

就是这样,我希望有一种方法可以在第一个查询中返回章节

标签: mongoosesubdocument

解决方案


推荐阅读