使用简单的mongo / monk findAndModify查询问题

时间:2015-07-21 02:39:35

标签: node.js mongodb upsert monk

只是一个注释我对mongo来说相当新,对使用node / js来说更新。

我尝试编写查询以插入新文档或更新我的集合中现有的文档。

该集合的拟议结构是:

{ _id: xxxxxxx, ip: "xxx.xxx.xxx.xxx:xxxxxx", date: "xx-xx-xx xxxx" }

请注意,我的意图是为_id而不是内部ObjectId存储一个固定长度的int(这可能/被认为是不好的做法?)。 int保证是唯一的,来自其他来源。

var monk = require('monk');
var db = monk('localhost:27017/cgo_schedule');

var insertDocuments = function(db, match) {
    var db = db;
    var collection = db.get('cgo_schedule');
    collection.findAndModify(
      {
        "query": { "_id": match.matchId },
        "update": { "$set": { 
            "ip": match.ip,
            "date": match.date
            },
        "$setOnInsert": {
          "_id": match.matchId,
        }},
        "options": { "new": true, "upsert": true }
      },
      function(err,doc) {
        if (err) throw err;
        console.log( doc );
      }
  );
}

然而,这根本不起作用。它不会向数据库插入任何内容,但它也没有错误,所以我不知道我做错了什么。

输出(console.log (doc))为空。

我做错了什么?

1 个答案:

答案 0 :(得分:3)

Monk文档帮助不大,但根据source codeoptions对象必须作为单独的参数提供。

所以你的电话应该是这样的:

collection.findAndModify(
    {
        "query": { "_id": match.matchId },
        "update": { 
            "$set": { 
                "ip": match.ip, 
                "date": match.date 
            }
        }
    },
    { "new": true, "upsert": true },
    function(err,doc) {
        if (err) throw err;
        console.log( doc );
    }
);

请注意,我删除了$setOnInsert部分,因为_id始终包含在带有upsert的插入内。

相关问题