alexislg
alexislg

Reputation: 1016

update a subfield with mongoose

I have a Node.js mongoose schema that looks like this:

var Schema = mongoose.Schema;
var playersSchema = new Schema({
    login: String, 
    pwd: String,
    game: {
        lat: Number,
        lon: Number,
        speed: Number,
        money: Number
    }
});

I want to update only the game.money field of a given element. How can I do that with findByIdAndUpdate ?

Upvotes: 1

Views: 1633

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

MongoDB supports "dot notation" for specifying fields in sub-documents. The same principle applies to either a plain object or an array of objects:

Model.findByIdAndUpdate(id,{ "$set": { "game.money" },function(err,doc) {

});

The $set operator also only updates the specified field or fields without affecting the rest of the document and overwriting the full content.

Also see other field update operators such as $inc to increment an existing number, either up or down.

Upvotes: 4

Related Questions