編輯添加了 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
}
uj5u.com熱心網友回復:
填充 refs 陣列的作業方式與單個 ref 相同。只需在查詢上呼叫 populate 方法,就會回傳一個檔案陣列來代替原始_id的。
在你的情況下,這將是:
const populated = await author.populate({path: 'books', select: 'name description -_id'});
uj5u.com熱心網友回復:
嘿,我已經修改了你的代碼,嘗試使用這個
這是您的作者架構檔案
const Schema = mongoose.Schema;
const authorSchema = mongoose.Schema({
_id:{
type: String,
required: true,
unique: true,
trim: true
},
name: {
type: String,
required: true,
trim: true
},
books: [{
type: Schema.Types.ObjectId,
ref: "bookSchema"
}]
}, {_id:false})
const Author = mongoose.model('Author', authorSchema)
module.exports = {Author}
這是你的路線
AuthorRouter.get('/authors/:id', async(req, res)=>{
const authorID = req.params.id
try {
const author = await Author.findById(authorID)
try {
const populated = await author.find().populate('books');
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')
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/399954.html
上一篇:在Moongose上查找一位用戶
