2012-03-11 76 views
1

我使用MongoDB的我site.When我尝试运行“findAndModify”功能,我总是那个文件夹是“未定义”:使用“findAndModify”有关MongoDB

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

    return doc.next; 
} 

问:我在想什么?

+0

什么版本的MongoDB是您目前以怎样的驱动程序运行?如果你通过shell来试试这个,你的结果是什么? – Bill 2012-03-11 14:17:02

+0

我使用2.0.3。如果我检查壳体,它的工作原理 – user541847 2012-03-12 15:36:20

回答

1

你没有错过任何东西,upsert等于true findAndModify应该总是返回文档..即使没有匹配的查询。

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

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

2

我刚刚试图从MongoDB文档实现相同的计数器示例代码的这个问题。

如果您使用的是mongojs驱动程序,你需要使用一个回调作为函数不返回任何内容:

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); 
    }); 
-3

打破我的头相当长的一段时间后,我有点更改为1,并工作.....

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

请解释如何解决问题中描述的问题。 – nabinca 2015-09-24 18:34:58