Search code examples
node.jsmongodbmongoosemongoose-schemamongoose-populate

How to dynamically populate array of objects in mongoose?


I am trying to dynamically populate array of objects in mongoose. On my user model I want an array that contains all posts that user made. The problem is that I have multiple types of posts.

Different post models:

const ImagePost = mongoose.model('ImagePost', new Schema({ url: String }))

const TextPost = mongoose.model('TextPost', new Schema({ text: String }))

My user model looks like this:

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)

How can I get the user from my database and automatically populate the posts the user made?

The whey I think it should work is this but for some reason it doesn't do anything:

User.findById('5d302c7caf1b8906ccb611b6').populate('posts.postId')

Solution

  • Changing your refPath from postModel to posts.postModel may solve your problem.