Reputation: 340
I am a little confused about these mongoose functions: update, updateOne, and updateMany.
can someone clarify what is the difference between them.
updateMany: updates all the documents that match the filter.
updateOne: updates only one documnet that match the filter.
what about the update?
Upvotes: 8
Views: 10572
Reputation: 102507
Same as
update()
, except MongoDB will update all documents that match filter (as opposed to just the first one) regardless of the value of themulti
option.
Same as
update()
, except it does not support themulti
oroverwrite
options.
Take a look at the source code of these three methods:
update
:
Model.update = function update(conditions, doc, options, callback) {
_checkContext(this, 'update');
return _update(this, 'update', conditions, doc, options, callback);
};
updateMany
:
Model.updateMany = function updateMany(conditions, doc, options, callback) {
_checkContext(this, 'updateMany');
return _update(this, 'updateMany', conditions, doc, options, callback);
};
updateOne
:
Model.updateOne = function updateOne(conditions, doc, options, callback) {
_checkContext(this, 'updateOne');
return _update(this, 'updateOne', conditions, doc, options, callback);
};
They call the _update
function with different op
parameter finally.
_update
:
/*!
* Common code for `updateOne()`, `updateMany()`, `replaceOne()`, and `update()`
* because they need to do the same thing
*/
function _update(model, op, conditions, doc, options, callback) {
const mq = new model.Query({}, {}, model, model.collection);
callback = model.$handleCallbackError(callback);
// gh-2406
// make local deep copy of conditions
if (conditions instanceof Document) {
conditions = conditions.toObject();
} else {
conditions = utils.clone(conditions);
}
options = typeof options === 'function' ? options : utils.clone(options);
const versionKey = get(model, 'schema.options.versionKey', null);
_decorateUpdateWithVersionKey(doc, options, versionKey);
return mq[op](conditions, doc, options, callback);
}
Upvotes: 10