我正在通过MERN堆栈为goodreads创建模拟,当我使用populate检索特定用户的书籍时,它返回空数组,我已经做了很多搜索但是徒劳无功这里是我的模型
const userSchema =new mongoose.Schema({
firstName:{
type:"string",required:true
},
books:[{
book:{type:mongoose.Schema.Types.ObjectId,ref:'Book'},rate:Number,shelve:''
}]});
这是书籍模型
const bookSchema =new mongoose.Schema({
title :{
type:"string",required:true
}});
这就是我使用populate的方式
router.get("/one", (req, res, next) => {
User.find({firstName : "John"}).populate("books").exec(function (err, user) {
res.json(user)
});
})
这是结果json
[{"_id":"5c70f299ef088c13a3ff3a2c","books":[]}]
你正在引用books数组中的对象book
,所以你需要填充books.book
。
User.find({firstName : "John"}).populate("books.book").exec(function (err, user) {
res.json(user)
});