krl krl - 2 months ago 27
Node.js Question

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
?

Answer

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 object is at the previous one.