WHITECOLOR
WHITECOLOR

Reputation: 26122

Mongoose populates field with null

I have a mongoose schema:

  mongoose.Schema({
    state: {
        type: {
           action: 'string' , 
           user: {type: mongoose.Schema.Types.ObjectId, 
           ref: 'User'}, 
           at: 'date'
       },
   default: {}
   },
   log: [{
           action: 'string' , 
           user: {type: mongoose.Schema.Types.ObjectId, 
           ref: 'User'}, 
           at: 'date'
       }]
})

Trying to populate it

Model.findById(id).populate('state.user').populate('log.user').exec(cb)

In query result "user" field of log items is populated correctly and "state.user" is null. What can be the problem?

Upvotes: 1

Views: 1142

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311835

For simple embedded objects like state, define the structure without using type:

mongoose.Schema({
    state: {
       action: 'string' , 
       user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, 
       at: 'date'
    },
    log: [{
           action: 'string' , 
           user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, 
           at: 'date'
    }]
})

populate('state.user') should work fine with that.

Upvotes: 2

matthewtole
matthewtole

Reputation: 3247

In your schema, you have state.type.user, but your call to populate refers to state.user. The path in the populate call doesn't match the schema.

It should be Model.findById(id).populate('state.type.user').populate('log.user').exec(cb)

Upvotes: 1

Related Questions