【发布时间】:2021-12-29 18:32:48
【问题描述】:
编辑添加了 mongoose.model。
我对 mongodb 和 mongoose 还是很陌生。我无法将书籍填充给猫鼬中的作者。 任何人都可以帮助我吗?这是我的代码。我删除了不必要的字段
const authorSchema = mongoose.Schema({
_id:{
type: String,
required: true,
unique: true,
trim: true
},
name: {
type: String,
required: true,
trim: true
},
books: [{
type: String,
ref: "Book"
}]
}, {_id:false})
const Author = mongoose.model('Author', authorSchema)
module.exports = {Author}
我的图书架构如下所示
const bookSchema = mongoose.Schema({
_id:{
type:String,
required:true,
unique:true,
trim: true
},
name: {
type: String,
required: true,
trim: true,
unique: true
},
description:{
type: String,
trim: true,
default: 'No description specified'
},
datePublished: {
type: Date,
trim: true,
default: '01/01/2001'
},
author:{
type: String,
ref: 'Author',
required: true
}
}, {_id:false})
const Book = mongoose.model('Book', bookSchema)
module.exports = {Book}
这是将它们填充在一起的路线
AuthorRouter.get('/authors/:id', async(req, res)=>{
const authorID = req.params.id
try {
const author = await Author.findById(authorID)
try {
const populated = await author.populate({path: 'books.book', select: 'name description -_id'})
console.log(populated);
res.status(201).send(populated)
} catch (e) {
res.status(401).send(`${e}\n Unable to populate categories`)
}
} catch (error) {
res.status(401).send('Unable to find author')
}
})
输出如下是空书籍数组:
{
"_id": "123",
"name": "testuser",
"books": [],
"__v": 0
}
【问题讨论】:
-
你在代码的什么地方指定了
Mongoose.model函数? -
@Tyler2P 在模式的末尾。我刚刚将它们添加到代码中
标签: node.js mongodb express mongoose