Save/update changes of a populated document

GameSession : {
    _id: "e055dbe445dda0332dc7cbd4c"
    amount: 500,
    location: {type: mongoose.Schema.ObjectId, ref: 'Location'},
    madeBy: {type: mongoose.Schema.ObjectId, ref: 'User'},
}

User: {
    _id: "e055dfesd445dda0332dc7et54ge"
    points: 5000
}

I get the sessions and I populate the document

let sessions = await GameSession.find({location: location._id}).populate('madeBy', '_id points').exec()

I get the data correctly. Now if I make some changes to the populated data like…

sessions.madeBy.points = 200

Is there any way to save this change?

1 Like

I would look into the $set operator to update a document. Here you can set a new value of an existing field or add a new field to a document.

It looks like you’re using mongoose they have an example of use $set.

1 Like