node.js - 在 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 找到特定的章节?
解决方案
您正在使用章节 ID 的 findById 搜索 Book,它不会给出结果,因为它不是 Book Id,
您将需要为此$elemMatch
使用
推荐阅读
- c++ - 从 C++ 文件中搜索艺术家姓名和歌曲
- javascript - 基于属性组合对象数组内部数组
- python - 如果字符串不是字母数字,则无法阻止函数工作
- python - 如何制作由(例如)3 的倍数组成的 Python 数组?
- python - 在神经网络中,如何通过矩阵乘法计算梯度?为什么?
- python - 模块 'pandas' 没有 'read_csv' 成员 pylint(no-member)
- python-3.x - 由于路径问题,无法将 python 项目变成可执行文件?
- javascript - M 寻找可以根据数据库中可用数据在图像上显示热点的方法
- python - 模块 fbprophet 与 python 3.7.* 及更高版本不兼容?
- c++ - Boost Spirit X3:将(一些)空格解析为枚举