【发布时间】:2021-01-02 17:32:44
【问题描述】:
我有一个集合模型,它有一个包含项目模型数组的项目属性。
const CollectionSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
items : [{type : mongoose.Schema.Types.ObjectId, ref: 'Item'}]
});
我尝试填充 items 数组以获取 objectId 的属性,但 items 数组将返回空。 (下面的代码是我如何填充 items 数组。我首先使用 req.body.search 通过 _id 找到了我正在寻找的集合。然后我运行 .populate("items") 以填充 items 数组。我得到的是一个空的 items 数组。)
userRouter.post('/iList', passport.authenticate('jwt', {session: false}), (req, res) => {
Collection.findById({_id : req.body.search}).populate("items").exec((err, document) => {
if(err)
res.json(err)
else
res.json({item: document})
})
});
我知道我的 items 数组不是空的,因为我可以在 mongoDB 上检查它是否已满。 The image of my mongoDB collection with an items array that isn't empty.
奇怪的是,如果我将“集合”放入 .populate 参数中,我的 Items 数组确实会返回内容,但它只返回 ObjectID 而不是实际的对象属性。我很困惑为什么 .populate("items") 不起作用。
【问题讨论】:
标签: mongodb mongoose mongoose-schema mongoose-populate