使用猫鼬查询嵌入式文档数组



这是我的嵌入文档的文档:

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

为了通过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章节数组中找到特定的

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('/')
}
})

如问题中所述,为了从chapters数组中获得特定的chapter,可以使用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,
},
];

最新更新