【发布时间】:2019-11-27 05:51:49
【问题描述】:
我正在尝试在猫鼬中动态填充对象数组。在我的用户模型上,我想要一个包含用户发布的所有帖子的数组。问题是我有多种类型的帖子。
不同的帖子模型:
const ImagePost = mongoose.model('ImagePost', new Schema({ url: String }))
const TextPost = mongoose.model('TextPost', new Schema({ text: String }))
我的用户模型如下所示:
const userSchema = new Schema({
userName: {
type: String,
required: true
},
posts: [{
postId: {
type: Schema.Types.ObjectId,
required: true,
refPath: "postModel"
},
postModel: {
type: String,
required: true,
enum: ['ImagePost', 'TextPost']
}
}]
})
const User = mongoose.model('User', userSchema)
如何从我的数据库中获取用户并自动填充用户发布的帖子?
我认为它应该起作用的乳清是这样的,但由于某种原因它什么也没做:
User.findById('5d302c7caf1b8906ccb611b6').populate('posts.postId')
【问题讨论】:
标签: node.js mongodb mongoose mongoose-schema mongoose-populate