【问题标题】:Collection.upsert() vs Collection.update() with "upsert: true"Collection.upsert() 与 Collection.update() 与“upsert: true”
【发布时间】:2016-01-04 04:27:28
【问题描述】:

我在 Meteor 中使用 MongoDB。我发现更新(如果已经存在)数据或插入集合update() 可以与upsert: true 一起使用。还有一个名为upsert() 的方法也可以用来更新/插入记录。

代码:(来自 Meteor)

使用update

Collection.update({
    _id: id
}, {
    $set: {
        content: 'SomeText'
    }
}, {
    upsert: true
});

使用upsert

Collection.upsert({
    _id: id
}, {
    $set: {
        content: 'SomeText'
    }
});

问题:

  1. 区别:upsert 标志设置为trueupdate()upsert() 有什么区别?
  2. 用例: 何时应使用update()upsert()

【问题讨论】:

标签: mongodb meteor


【解决方案1】:

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

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

所以upsert 只是update 的简写,选项upsert 设置为true。 没有什么不同,你可以使用任何你喜欢的功能

【讨论】:

  • 所以,upsert 属于 update 上的 Meteor 层。如果我将upsert: false 传递给upsert() 会怎样?
  • 是的,即使您将upsert: false 传递给upsert(),它也会被_.extend 覆盖,因为{_returnObject: true, upsert: true } 是最后一个来源(underscorejs.org/#extend)
【解决方案2】:

后一个 upsert 是 javascript shell bulk operation 的一个组件。我确定它没有被任何驱动程序暴露。

【讨论】:

  • 在 Meteor 中,允许在 Collection 上使用。
猜你喜欢
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
  • 2021-03-02
  • 1970-01-01
  • 2016-03-27
  • 2014-10-08
相关资源
最近更新 更多