【问题标题】:populate in mongoose returns empty array, i'm Stucked在猫鼬中填充返回空数组,我卡住了
【发布时间】:2019-07-17 08:20:26
【问题描述】:

我正在通过 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.js mongodb express mongoose mongoose-populate


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回复,我已经尝试过了,它给了我这样的 _id 数组 [{"_id":"5c70f299ef088c13a3ff3a2c","books":[{"_id":"5c708c0077a0e703b15310b9"} ,{"_id":"5c708c0077a0e703b15310ba"}] 但我需要像标题这样的内容
    • 好的,然后尝试使用.populate('books.book','title'),它可能会起作用。
    • 仍然返回 Id :/
    猜你喜欢
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2019-07-17
    • 2023-03-21
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    相关资源
    最近更新 更多