用简单的mongo/monk findAndModify查询发出问题 [英] Issue with a simple mongo/monk findAndModify query

查看:147
本文介绍了用简单的mongo/monk findAndModify查询发出问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅需说明一下,我对mongo还是相当陌生,尤其是对使用node/js来说非常新.

Just a note I am fairly new to mongo and more notably very new to using node/js.

我正在尝试编写查询以插入新文档或更新我的收藏集中的现有文档.

I'm trying to write a query to insert new documents or update already existing documents in my collection.

该馆藏的拟议结构为:

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

请注意,我的意图是为_id存储固定长度的int而不是内部ObjectId(这是否可能/被认为是不正确的做法?).该int保证是唯一的,并且来自另一个来源.

Note that my intention is a store an fixed length int for the _id rather than the internal ObjectId (is this possible/considered bad practice?). The int is guaranteed to be unique and comes from another source.

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 );
      }
  );
}

但是,这根本不起作用.它不会向数据库中插入任何内容,但是也不会产生任何错误,因此我不知道自己在做什么错.

This doesn't work at all however. It doesn't insert anything to the database, but it also gives no errors, so I have no idea what I'm doing wrong.

(对于console.log (doc)的)输出为空.

我在做什么错了?

推荐答案

和尚文档并没有多大帮助,但根据

The Monk docs aren't much help, but according to the source code, the options object must be provided as a separate parameter.

因此您的通话应改为:

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

Note that I removed the $setOnInsert part as the _id is always included on insert with an upsert.

这篇关于用简单的mongo/monk findAndModify查询发出问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆