node.js - 简单 mongo/monk findAndModify 查询的问题

标签 node.js mongodb upsert monk

请注意,我对 mongo 相当陌生,尤其是对使用 Node/js 非常陌生。

我正在尝试编写一个查询来插入新文档或更新我的集合中已有的文档。

建议的集合结构是:

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

请注意,我的意图是为 _id 存储固定长度的 int,而不是内部 ObjectId(这可能/被认为是不好的做法吗?)。 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))为空。

我做错了什么?

最佳答案

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 的插入中。

关于node.js - 简单 mongo/monk findAndModify 查询的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31529471/

相关文章:

javascript - 使用 Node 本地化

javascript - 在 Node.js 中读取环境变量

javascript - 不知道如何消除 MongoDB 中的重复键错误

mongodb - 如何使用 MongoDB 制作对象 ID 数组的 "join"

node.js - MongoError : connect ECONNREFUSED 127. 0.0.1:27017

elasticsearch - Kafka 连接到 ElasticSearch 是否可以进行更新

postgresql - 环回返回 PU/UPSERT 上的现有记录

javascript - Jasmine Node 选项 : Unexpected identifier error while executing protractor protractorConfig. js

node.js - 区分nodejs请求和响应

sql - Postgres UPSERT(INSERT 或 UPDATE)仅当值不同时