Mongoose中update、updateOne和updateMany函数的区别

8

我对这些mongoose函数: update、updateOne和updateMany有点困惑。

有人能否澄清它们之间的区别。

updateMany:更新所有与筛选器匹配的文档。

updateOne:仅更新与筛选器相匹配的一个文档。

那么update呢?


1
嗨Heybat,注意mongoose正在弃用update方法,"请使用updateOne()、updateMany()或replaceOne()替换update()",请参见https://mongoosejs.com/docs/deprecations.html。 - mariano_c
1个回答

10
  • Model.updateMany()
    update()相同,除了无论multi选项的值为何,MongoDB都将更新匹配筛选器的所有文档。

update()相同,除了无论multi选项的值为何,MongoDB都将更新匹配筛选器的所有文档。

update()相同,但不支持multioverwrite选项。

请查看这三种方法的源代码:

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);
};

他们最终使用不同的op参数来调用_update函数。 _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);
}

源代码


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接