【问题标题】:How to get count of upserted documents with $setOnInsert?如何使用 $setOnInsert 计算插入文档的数量?
【发布时间】:2014-07-22 05:05:33
【问题描述】:

我在猫鼬中使用以下更新查询:

Doc.findOneAndUpdate({
  name: 'Ekik'
}, {$setOnInsert: {key: value}}, {upsert: true, new: true}, function (err, doc) {
     // How to get upserted count here?
     console.log(doc.isNew); // always true either document upserted or don't
});

我需要计算插入文档的数量。我该怎么办?

【问题讨论】:

  • 您确实意识到您将 ObjectId 值作为查询传递?要么你只是生成了这个,所以 一个插入,或者你从某个地方得到它并期望它存在,所以 一个更新
  • 我需要像下面的stackoverflow.com/questions/16358857/… 一样破解,但我只需要知道任一文档已插入
  • 再看评论,很清楚。您正在通过 _id 查找。它是否存在于集合中。方法名称中的“一”应该提示您有多少。
  • 不幸的是,我不明白我怎么能得到 upserted 文档。要么我使用 {new: true} 我总是得到一些文件,但我不知道它是被插入还是存在
  • new: true 是默认修改的文档。尝试新的:false

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

回调中findOneAndUpdate() 的返回签名是errdocument 被修改或插入。还有一种默认情况是返回的文档是“修改后的”文档,除非您将参数设置为false

看一个例子:

    var mongoose = require('mongoose'),
        Schema = mongoose.Schema,
        ObjectId = require('mongodb').ObjectID;

    mongoose.connect('mongodb://localhost/test');

    var uptestSchema = new Schema({
      value: Number
    });

    var Uptest = mongoose.model( "uptest", uptestSchema, "uptest" );

    var id = new ObjectId("538c1fea6369faeced1b7bfb");

    console.log( id )

    Uptest.findOneAndUpdate(
      { _id: id },
      { "$setOnInsert": { value: 3 } },
      { upsert: true, new: false },
      function(err, doc) {

        console.log( doc );

      }
    );

现在,如果给定_id 的文档存在,那么我希望看到没有修改的“原始”文档返回。反正那里只有$setOnInsert,所以不会有任何变化。

如果发生“upsert”,则“原始”文档的返回值将是null,因为最初没有文档。这就是告诉您该操作导致“更新插入”并创建了一个新文档的原因。

【讨论】:

  • 感谢您的回复,但为什么我们无法知道使用 isNew 值更新插入的任一文档。 (我已经更新了帖子)
  • @Erik 正如我告诉你的,当new: false 然后一个新文档导致回调中的doc 值为null。否则为原始文件。 null 表示插入了一个新文档。
  • 是的,我明白,但我需要在回调方法中插入文档。我怎么能得到它
  • @Erik 您唯一的参数是_id$setOnInsert,所以这些是文档中唯一的值。或者保留默认的new: true,如果$setOnInsert 值没有反映在返回的文档中,那么它不会被插入而只是更新。这只是您选择哪种方法的逻辑案例。
  • 实际上我没有查询和更新文档的对象(这只是示例)所以有没有可能知道我需要什么?
猜你喜欢
  • 2017-12-10
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-20
  • 2011-11-11
相关资源
最近更新 更多