用猫鼬查询一系列嵌入式文档

时间:2020-09-09 07:44:23

标签: node.js mongodb mongoose

这是我的带有嵌入式文档的文档:

{
    "_id": "5f56f8e66a7eee227c1acc0a",
    "title": "Book1",
    "author": "Author1",
    "chapters": [{
        "_id": "5f56fa47a78fbf03cc32d16d",
        "title": "Chapter1",
        "number": 1
    }, {
        "_id": "5f56fad10820300de031317f",
        "title": "Chapter2",
        "number": 2,
    }]
    }

要从 chapters 数组中找到特定的 chapter ,请使用id,我编写了以下代码:

router.get('/:id', async function (req, res) {
try {
    const id = req.params.id
    await Book.findById(id, function (err, chapter) {
        console.log(chapter)
    })
} catch (error) {
    res.redirect('/')
}
})

我找到了一个空数组[]。但我希望得到这样的结果:

{
    "_id": "5f56fa47a78fbf03cc32d16d",
    "title": "Chapter1",
    "number": 1
}

我应该怎么做才能从数组中通过id找到特定的

2 个答案:

答案 0 :(得分:0)

router.get('/:id', async function (req, res) {
try {
  const id = req.params.id
  // this is what you need to change
  await Book.find({ "chapters._id": id }, function (err, chapter) {
    console.log(chapter)
  })
} catch (error) {
  res.redirect('/')
}
})

答案 1 :(得分:0)

如问题中所述,为了从chapter数组中获取特定的chapters,可以使用Aggregate

const result = await Book.aggregate([
  {
    $match: {
      "chapters._id": mongoose.Types.ObjectId(id),
    },
  },
  { $unwind: "$chapters" },
  {
    $match: {
      "chapters._id": mongoose.Types.ObjectId(id),
    },
  },
  { $replaceWith: "$chapters" },
]);
console.log(result);

如果id一章在整个馆藏中是唯一的,那么结果将是其中包含一个chapter文档的数组

抽样结果:

[
  {
    _id: "5f56fa47a78fbf03cc32d16d",
    title: "Chapter1",
    number: 1,
  },
];