0

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')

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.