我正在通过 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
}});
这就是我使用填充的方式
router.get("/one", (req, res, next) => {
User.find({firstName : "John"}).populate("books.book").exec(function (err, user) {
res.json(user)
});
})
这是结果 JSON
[{"_id":"5c70f299ef088c13a3ff3a2c","books":
[{"_id":"5c708c0077a0e703b15310b9"},{"_id":"5c708c0077a0e703b15310ba"},
{"_id":"5c708c0077a0e703b15310bb"},{"_id":"5c708c0077a0e703b15310bd"}]}]
最佳答案
我认为这是您的 UserSchema
定义方式的问题。我的假设是,在 books
的定义中包含 rate
和 shelve
导致了问题。
尝试删除这些字段以开始,然后仅填充 books
而不是 books.book
。如果这有效,那么我真的会重新考虑将这些字段放在您拥有的地方。以我个人的观点,我认为它们在 BookSchema
中看起来更好,因为 UserSchema
中的每本书都有一个 rate
和 shelve
。希望这有帮助!!
关于node.js - 填充 mongoose 返回 _ids 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54841412/