【问题标题】:How to dynamically populate array of objects in mongoose?如何在猫鼬中动态填充对象数组?
【发布时间】: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


    【解决方案1】:

    将您的 refPathpostModel 更改为 posts.postModel 可能会解决您的问题。

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 2021-08-16
      • 2014-11-25
      • 1970-01-01
      • 2020-10-13
      • 2019-09-19
      • 2017-04-29
      相关资源
      最近更新 更多