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

col*_*ore 14 javascript mongodb node.js mongodb-query

我想用nodejS在mongodb做一个findAndModifiy,这是我的代码:

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);
};
Run Code Online (Sandbox Code Playgroud)

编辑:

尝试使用回调

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

但是给我错误需要删除或更新..但我正在做它..

Nei*_*unn 19

.findAndModify()节点本机驱动程序实现中的方法与mongo shell实现不同.要进行上述更新,您可以:

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

   }
);
Run Code Online (Sandbox Code Playgroud)

奇怪的是有些删除你在选项中指定所以同样会"删除"匹配的文档:

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

   }
);
Run Code Online (Sandbox Code Playgroud)

主要区别在于您没有为操作命名"关键"部分.


Pau*_*amp 9

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

上面的文档指定第二个参数是用于选择在多个文档与查询匹配时使用哪个文档的排序顺序.仅提供两个参数将导致"需要删除或更新"错误消息.

collection('MyCollection').findAndModify(
    { _id: "auto" },
    [],
    { $inc: { "bill": 1 } },
    { upsert: true, new: true },
    function(err,doc) {
       // work here
    }
);
Run Code Online (Sandbox Code Playgroud)