首页 > 解决方案 > 在 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 找到特定的章节?

标签: node.jsmongodbmongoose

解决方案


您正在使用章节 ID 的 findById 搜索 Book,它不会给出结果,因为它不是 Book Id,

您将需要为此$elemMatch使用

检查此Querying for Object in Mongoose Sub Array以供参考


推荐阅读