mongodb-js / mongoose-autopopulate

Always populate() certain fields in your mongoose schemas
Apache License 2.0
221 stars 36 forks source link

Populate after save not working for nested schemas / subdocuments #70

Closed bamoure closed 4 years ago

bamoure commented 4 years ago

Populating a document after an update through .save() fails with TypeError: Cannot read property 'length' of undefined.

I have a Schema like this:

const GameSchema: Schema = new Schema({
    players: [{
        type: Schema.Types.ObjectId,
        ref: 'User',
        autopopulate: { select: ['name', '_id'] },
        required: true,
        default: []
    }],
    state: [{
        cards: [{
            player: String,
            card: {
                type: Schema.Types.ObjectId,
                ref: 'Card',
                autopopulate: { select: ['name', '_id'] }
            },
            revealed: Boolean
        }],
        turn: {
            type: Number
        }
    }]
})

And a document I'm fetching and updating by pushing a new value to the players array, while state is an empty array. Before saving it looks like this:

{
  players: [
    { _id: 5e79c3538da6250047d4dd43, name: 'tester' },
    { _id: 5e79c3648da6250047d4dd45 }
  ],
  _id: 5e79c35a8da6250047d4dd44,
  state: [],
  __v: 3
}

When saving, the post save handler in index.js fails when trying to populate the Card references on this.get(options.path) (line 64) as the path 'state.cards.card' is undefined. I think before getting the length of the object, it should check that it exists.

I'm using version 0.12.0 of the plugin and mongoose 5.9.4.