使用';查找和修改';关于mongodb

使用';查找和修改';关于mongodb,mongodb,Mongodb,我在我的网站上使用mongodb。当我尝试运行“findAndModify”时‬" 函数我总是得到文档是“未定义的”: function counter(name) { var doc = this.db.collection('counter').findAndModify( { query: { _id: name }, update: { $inc: { next: 1} },

我在我的网站上使用mongodb。当我尝试运行“findAndModify”时‬" 函数我总是得到文档是“未定义的”:

function counter(name) {
    var doc = this.db.collection('counter').findAndModify(
                { query: { _id: name }, 
                  update: { $inc: { next: 1} }, 
                  new: true, 
                  upsert: true });

    return doc.next;
}

问:我遗漏了什么?

您没有遗漏任何内容,upsert等于true find,modify应始终返回文档..即使查询中没有匹配项

但是,切分和findAndModify存在局限性——您的查询应该始终包含切分键mb,这是一个问题


此命令也可用于版本>=1.3的mongodb。如果您使用旧的mongodb,只需将其更新到最新版本(2.0.3),它应该可以工作。(我已经在1.8和2.0上进行了测试)

我在尝试从mongodb文档中实现相同的计数器示例代码时遇到问题

如果正在使用驱动程序,则需要使用回调函数,因为该函数不返回任何内容:

this.db.collection('counter').findAndModify({
    query: { _id: name }, 
    update: { $inc: { next: 1} }, 
    new: true, 
    upsert: true 
    },
    function(err, doc){
        console.log('the id is: '+doc.next);
    });

在打破我的头相当长一段时间后,我改变排序为1,它工作了

counters.findAndModify({ _id: { $eq: "virtualcurrency" } }, { '_id': 1 }, { $inc: { seq: 1 } }, { new: true }, function (err, result) {

您当前正在运行哪个版本的MongoDB以及使用哪个驱动程序?如果您通过shell尝试此操作,您的结果如何?我使用2.0.3。如果我签入shell,请解释这是如何解决问题中描述的问题的。