发出一个简单的mongo /修士findAndModify查询

只是一个说明,我对mongo来说还是比较新的,对于使用node / js来说更是显得非常新颖。

我试图编写一个查询来插入新文档或更新我的集合中已经存在的文档。

拟议的收集结构是:

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

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

 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文档没有多大帮助,但根据源代码 , 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始终包含在用插入插入。