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
?
When you create an instance of a Mongoose model using new , calling save() makes Mongoose insert a new document. If you load an existing document from the database and modify it, save() updates the existing document instead.
Mongoose save with an existing document will not override the same object reference. Bookmark this question.
Mongoose transforms the result of findOneAndUpdate() by default: it returns the updated document.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With