用猫鼬填充返回空数组,我被卡住了

时间:2019-02-23 10:29:36

标签: node.js mongodb express mongoose mongoose-populate

我正在通过MERN堆栈创建用于readreads的模拟 当我使用填充来检索特定用户的书时,它返回空数组,我做了很多搜索但徒劳 这是我的模特

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
}});

这就是我使用填充方式

router.get("/one", (req, res, next) => {
User.find({firstName : "John"}).populate("books").exec(function (err, user) { 
    res.json(user)
 });
})

这是生成的json

[{"_id":"5c70f299ef088c13a3ff3a2c","books":[]}]

1 个答案:

答案 0 :(得分:0)

您要在books数组中引用对象book,因此需要填充books.book

User.find({firstName : "John"}).populate("books.book").exec(function (err, user) { 
   res.json(user)
 });
相关问题