2015-07-21 29 views
1

只是說明我是相當新的蒙戈和更值得注意的是很新的使用節點/ JS。問題用一個簡單的蒙戈/和尚findAndModify查詢

我想編寫一個查詢我的收藏品中插入新的文檔或更新現有的文件。

收集的擬議結構是:

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

請注意,我的意圖是一種存儲在_id而不是內部的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))爲空。

我在做什麼錯?

回答

3

Monk文檔沒有多大幫助,但根據source code,必須提供options對象作爲單獨的參數。

所以你的電話應該是這樣的,而不是:

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

+0

乾杯@JohnnyHK,做工精細。 :) – anditpainsme