goku
goku

Reputation: 156

What's the difference between normal update and updating using $set operator?

Normal method:

module.exports = (_id, newInfo) => {
    return User.update( {_id} , newInfo);
};

Using $set operator:

module.exports = (_id, newInfo) => {
    return User.update( {_id} , {$set: newInfo} );
};

Upvotes: 1

Views: 753

Answers (2)

andrewgi
andrewgi

Reputation: 632

$Set creates a new field if there is no existing one

If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint. If you specify a dotted path for a non-existent field, $set will create the embedded documents as needed to fulfill the dotted path to the field.

https://docs.mongodb.com/manual/reference/operator/update/set/

Upvotes: 1

Christos
Christos

Reputation: 53958

As it stated here:

Updating without the use of $set,

if the replacement object is a document, the matching documents will be replaced (except the _id values if no _id is set)

Whereas we use the $set,

To update only selected fields, $set operator needs to be used. Following replacement object replaces author value but leaves everything else intact.

Upvotes: 3

Related Questions