我对这些猫鼬函数有点困惑:update、updateOne 和 updateMany。
有人可以澄清它们之间有什么区别吗?
updateMany:更新所有与过滤器匹配的文档。
updateOne:仅更新与过滤器匹配的一个文档网。
更新怎么样?
sli*_*wp2 10
与 相同
update(),但 MongoDB 将更新与过滤器匹配的所有文档(而不是仅第一个文档),无论选项的值如何multi。
与 相同
update(),但它不支持multi或overwrite选项。
看一下这三个方法的源码:
update:
Model.update = function update(conditions, doc, options, callback) {
_checkContext(this, 'update');
return _update(this, 'update', conditions, doc, options, callback);
};
Run Code Online (Sandbox Code Playgroud)
updateMany:
Model.updateMany = function updateMany(conditions, doc, options, callback) {
_checkContext(this, 'updateMany');
return _update(this, 'updateMany', conditions, doc, options, callback);
};
Run Code Online (Sandbox Code Playgroud)
updateOne:
Model.updateOne = function updateOne(conditions, doc, options, callback) {
_checkContext(this, 'updateOne');
return _update(this, 'updateOne', conditions, doc, options, callback);
};
Run Code Online (Sandbox Code Playgroud)
他们最终调用_update具有不同op参数的函数。
_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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8528 次 |
| 最近记录: |