首页 > 解决方案 > 在猫鼬中填充返回空数组,我被卡住了

问题描述

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

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":[]}]

标签: node.jsmongodbexpressmongoosemongoose-populate

解决方案


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

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

推荐阅读