krl
krl

Reputation: 5296

Mongoose findByIdAndUpdate removes not updated properties

I have the following Mongoose model:

var mongoose = require('mongoose');

var userSchema = mongoose.Schema({
    facebook: {
        name: String,
        email: String,
        customerId: String
    }
});

var User = mongoose.model('User', userSchema);

When I update a part of this document using findByIdAndUpdate

User.findByIdAndUpdate(id, { 
    $set: { 
        facebook: {
            name: name 
         }
    }
});

name gets updated, while email and customerId get removed (unset?).

I didn't find this documented.

Is there a way to update only specific document properties with findByIdAndUpdate?

Upvotes: 13

Views: 8647

Answers (1)

Vivek Bajpai
Vivek Bajpai

Reputation: 1615

FindByIdAndUpdate is actually Issues a mongodb findAndModify update command by a documents id.

The point is you are setting an object to overwrite the old object. if you want to update a field you need to modify your update object.

User.findByIdAndUpdate(id, { 
$set: { 
    'facebook.name':name       
 }
});

This will only update the name field keeping rest of the field of the old object.

Upvotes: 19

Related Questions