NodeJS和MongoDB FindAndModify()需要删除或更新

即时通讯试图做一个findAndModifiy与nodejS的mongodb,这是我的代码:

var nextBill = function (db, success, log) { var collection = db.collection('autoincrements'); log.debug('autoIncrementRepository', 'nextBill'); var result = collection.findAndModify({ query: { _id: 'auto' }, update: { $inc: { bill: 1 } }, new: true }); success(result.bill); }; 

编辑:

尝试回拨

 collection.findAndModify({ query: { _id: 'auto' }, update: { $inc: { bill: 1 } }, new: true }, function (e, result) { success(result.budget); }); 

但给我的错误需要删除或更新..但IM即时做..

节点本地驱动程序实现中的.findAndModify()方法与mongo shell实现不同。 要执行上面的更新,请执行以下操作:

 collection.findAndModify( { "_id": "auto" }, { "$inc": { "bill": 1 } }, function(err,doc) { // work here } ); 

奇怪的是要删除你在选项中指定,所以同样会“删除”匹配的文件:

 collection.findAndModify( { "_id": "auto" }, { "$inc": { "bill": 1 } }, { "remove": true }, function(err,doc) { // work here } ); 

主要的区别是你没有命名行动的“关键”部分。

http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify

这个上面的文档指定了第二个参数是sorting顺序,用于select使用哪个文档,如果多个文档匹配查询。 只给出两个参数将导致“需要删除或更新”的错误信息。

 collection('MyCollection').findAndModify( { _id: "auto" }, [], { $inc: { "bill": 1 } }, { upsert: true, new: true }, function(err,doc) { // work here } ); 
 Hi I have followed this and it worked perfectly. db.collection('test').findAndModify( {hello: 'world'}, // query [['_id','asc']], // sort order {$set: {hi: 'there'}}, // replacement, replaces only the field "hi" {}, // options function(err, object) { if (err){ console.warn(err.message); // returns error if no matching object found }else{ console.dir(object); } }); });