【问题标题】:using db.mycollection.distinct('field1', 'field2') with mongodb / mongoskin使用 db.mycollection.distinct('field1', 'field2') 与 mongodb / mongoskin
【发布时间】:2014-03-19 22:36:20
【问题描述】:

我在 user.js 文件的导出声明中有以下行:

 db.collection('myList').distinct('field1', 'field2'), function(err, items) {
        res.json(items);
 }

db 查找在 mongo 命令行中运行良好。但是,当我运行网页时,我得到:

 TypeError: string is not a function

目前我不确定如何进行。我应该在返回之前以某种方式将返回转换为字符串吗?

谢谢。

【问题讨论】:

    标签: node.js mongodb mongoskin


    【解决方案1】:

    您的问题似乎没有明确定义,请考虑逻辑:

    > db.info.insert({ field1: "this", field2: "that" })
    > db.info.insert({ field1: "this", field2: "another" })
    > db.info.insert({ field1: "this", field2: "that" })
    > db.info.insert({ field1: "this", field2: "another" })
    > db.info.distinct('field1', 'field2')
    [ "this" ]
    

    但你真正想要的是:

    db.info.aggregate([
       {$group: {_id: { field1: "$field1", field2: "$field2" } } }
    ])
    

    这给出了:

    {
        "result" : [
                {
                        "_id" : {
                                "field1" : "this",
                                "field2" : "another"
                        }
                },
                {
                        "_id" : {
                                "field1" : "this",
                                "field2" : "that"
                        }
                }
        ],
        "ok" : 1
    }
    

    组合字段的不同结果。

    我希望我们现在正在学习。

    【讨论】:

    • 谢谢你,但我的问题是如何使用 mongoskin 从 user.js 调用 myCollection.distinct()。
    • @user1901341 很好。但是您也被告知您的用例将不起作用。请改用aggregate。不同的使用参数是here
    【解决方案2】:

    出于某种奇怪的原因,MongoSkin 抽象不提供对 MongoDB 'distinct' 方法的访问。为了让工作与众不同,我不得不使用本机 MongoDB 集合,而不是抽象的 MongoSkin 集合。这是我的做法

    var store = mongo.db(connectionString, ackOptions); store.open(函数(错误,响应){ resp.collection(this.options.collection, {strict: true}, function(err, myCollection) { myCollection.distinct('tag',function(err,res){ 控制台日志(错误) 控制台.log(res) }) }); })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2012-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-10
      相关资源
      最近更新 更多