Collection.upsert()vs Collection.update()with"upsert:true"

Tus*_*har 1 mongodb meteor

我在Meteor中使用MongoDB.我发现要更新(如果已经存在)数据或插入集合update()可以使用upsert: true.还有一种方法upsert(),也可用于更新/插入记录.

代码:( 来自流星)

使用update:

Collection.update({
    _id: id
}, {
    $set: {
        content: 'SomeText'
    }
}, {
    upsert: true
});
Run Code Online (Sandbox Code Playgroud)

使用upsert:

Collection.upsert({
    _id: id
}, {
    $set: {
        content: 'SomeText'
    }
});
Run Code Online (Sandbox Code Playgroud)

题:

  1. 差异:标志设置为和之间update()有什么区别upserttrueupsert()
  2. 使用案例:何时应使用update()upsert()

som*_*llg 7

这是来自meteor源的mongo代码(https://github.com/meteor/meteor/blob/devel/packages/mongo/collection.js#L640)

Mongo.Collection.prototype.upsert = function upsert(
    selector, modifier, options, callback) {
  if (! callback && typeof options === "function") {
    callback = options;
    options = {};
  }

  const updateOptions = _.extend({}, options, {
    _returnObject: true,
    upsert: true
  });

  return this.update(selector, modifier, updateOptions, callback);
};
Run Code Online (Sandbox Code Playgroud)

所以upsert只需设置update选项upsert即可true.没有什么不同,你可以使用你喜欢的任何功能