Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 917
krl Avatar asked Oct 19 '14 07:10

krl


People also ask

Does update call save in Mongoose?

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.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question.

What does Mongoose Findbyidandupdate return?

Mongoose transforms the result of findOneAndUpdate() by default: it returns the updated document.


1 Answers

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.

like image 190
Vivek Bajpai Avatar answered Oct 16 '22 10:10

Vivek Bajpai