[英]Query in nested document in mongodb
這是我的貓鼬模式:
const chapterSchema = mongoose.Schema({
title: {
type: String
},
number: {
type: Number
}
})
const bookSchema = mongoose.Schema({
title: {
type: String
},
author: {
type: String
},
chapters: [chapterSchema]
})
const Book = mongoose.model('Book', bookSchema)
module.exports = Book
這是我的數據庫:
{
"_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) {
res.render('chapter.hbs', {
chapter: chapter
})
})
} catch (error) {
res.redirect('/')
}
})
根據章節id,我想要這個結果:
{
"_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 Books.aggregate([
{
$project: {
title: 1,
author: 1,
chapters: {
$filter: {
input: "$chapters",
as: "chapter",
cond: {
$eq: [
"$$chapter.id", id
]
}
}
}
}
}
])
} catch (error) {
res.redirect('/')
}
})
您可以使用aggregate()
函數,
$match
你的條件$filter
獲取特定章節 ID$replaceWith
替換 root 中的章節const id = mongoose.Types.ObjectId(req.params.id);
let chapter = await Book.aggregate([
{ $match: { "chapters._id": id } },
{
$replaceWith: {
$arrayElemAt: [
{
$filter: {
input: "$chapters",
cond: { $eq: ["$$this._id", id] }
}
},
0
]
}
}
]);
console.log(chapter);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.