首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongo findAndModify返回null

Mongo findAndModify返回null
EN

Stack Overflow用户
提问于 2015-08-25 18:10:44
回答 1查看 1.1K关注 0票数 2

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

代码语言:javascript
复制
  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应该返回修改后的对象。

EN

回答 1

Stack Overflow用户

发布于 2015-08-25 18:20:34

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

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

代码语言:javascript
复制
  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暗示这是来自" mongoose ",所以使用mongoose为.findOneAndUpdate()提供的本机方法

代码语言:javascript
复制
  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这样的大小写,而不是手动处理,那么最后可能就是你想要的。Mongoose会处理这个问题。本机驱动程序不会为您做这件事,因为它没有可引用的“模式”来实现“类型转换”。

因此,请使用应该支持的方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32201197

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档