【问题标题】:Mongo findAndModify returns nullMongoDB findAndModify 返回 null
【发布时间】:2015-11-18 23:48:33
【问题描述】:

Following.follow = function(id1, id2, cb) { console.log(id1) // 返回马特 console.log(id2) // 返回 Simone

  Following.collection.findAndModify({
      query: {
          ownerId: id1
      },
      update: {
          $addToSet: {
              followedBy: id2
          }
      },
      upsert: true,
      new: true
  }, function(err, result, lastErrorObject) {
      cb(err, result)
      console.log(result) // returns null
  })
}

我正在使用 Mocha 运行测试,而我的 findAndModify 函数只会返回 null。我阅读了文档,似乎无法弄清楚我做错了什么。如果找不到,则 Upsert 与 true 结合应该生成文档,并且 new 应该返回修改后的对象。

【问题讨论】:

  • 您在 cb 之后调用了 console.log... 如果交换最后两行会发生什么? console.log(result); cb(err, result);

标签: mongodb express mongoose mongodb-query mocha.js


【解决方案1】:

看起来这在很多方面都是错误的:

首先,这里的.findAndModify() 语法对任何node.js 驱动程序都无效,您可能指的是.findOneAndUpdate()

  Following.collection.findOneAndUpdate({
    { "ownerId": id1 }, 
    { "$addToSet": { "followedBy": id2 } },
    { 
      "upsert": true,
      "returnOriginal": false
    },
    function(err, result) {
      console.log(result);   // if you don't call before the callback it never gets called.
      cb(err, result);
    }
  );

第二种情况是.collection 暗示这是来自“猫鼬”,所以使用猫鼬的本机方法代替.findOneAndUpdate()

  Following.findOneAndUpdate({
    { "ownerId": id1 }, 
    { "$addToSet": { "followedBy": id2 } },
    { 
      "upsert": true,
      "new": true
    },
    function(err, result) {
      console.log(result);   // if you don't call before the callback it never gets called.
      cb(err, result);
    }
  );

如果您要传递需要大小写为 ObjectId 之类的字符串并且您没有手动处理该字符串,那么最后一个可能是您想要的。猫鼬处理这个。本机驱动程序不会为您执行此操作,因为它没有“模式”可以参考来计算“类型转换”。

所以使用应该支持的方法。

【讨论】:

    猜你喜欢
    • 2016-09-13
    • 2017-03-11
    • 2019-10-14
    • 2016-11-20
    • 2020-11-24
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多