Search code examples
node.jsmongodbmongoosemongoose-populate

How to refresh associated documents (previously populated) in Mongoose?


I have a Game model and a Player model. A game has an array of referenced players.

Inside of a game method one of the players is modified (not directly through this association instances but elsewhere). However, still inside the method, the version of the modified player data I have on this.players is outdated, from before the modification.

I am using mongoose-autopopulate. I tried calling this.populate('players') again but the array is not updated. I was wondering whether there is a way to refresh the association so I have the updated data.


Solution

  • I ended up setting autopopulate in the Schema so it always populates the attributes I want automatically. Something like that:

    const gameSchema = new Schema({
        _id: String, 
        players: [{
            type: Schema.Types.ObjectId,
            ref: 'Player',
            autopopulate: { maxDepth: 2 }
        }],
    
    ...