与数组不同的NodeJS Mongodb不起作用

时间:2018-01-22 07:24:11

标签: javascript node.js mongodb asynchronous callback

您好尝试使用与NodeJS(异步)的mongodb distinct查询。在Mongo的GUI中,此查询可以工作但在Node中它返回以下错误

TypeError: db.collection(...).distinct(...).toArray is not a function

错误在以下语句中返回:

mongo.connect(uri, function (err, db) {
    console.info('MONGODB START CHECK COLLECTIONS')
    var tasks = [   // Load businessrules
        function (callback) {
            db.collection('businessrules').find({typeBusinessRule: 'SpiderGraphExeption'}).toArray(function (err, businessrules) {
                if (err) return callback(err);
                locals.businessrules = businessrules;
                callback();
            });
        },
        // Load stgOmniTracker
        function (callback) {
            db.collection('stgOmniTracker').find({}).toArray(function (err, tickets) {
                if (err) return callback(err);
                locals.tickets = tickets;
                callback();
            });
        },
        // HERE STARTS THE ERROR
        function (callback) {
            db.collection('stgOmniTracker').distinct("Responsible Group").toArray(function (err, group) {
                if (err) return callback(err);
                locals.group = group;
                callback();
            });
        }
    ];
    console.info('--------------- START ASYNC ------------------------')
    async.parallel(tasks, function (err) {
        if (err) return next(err);
        var businessrules = locals.businessrules, tickets = locals.tickets, resultSet = {}, aggCountsPerDayCattegory = [], group = locals.group
        db.close()
}

我希望你能帮助我解决这个问题。曼尼谢谢

埃里克

2 个答案:

答案 0 :(得分:0)

db.collection('stgOmniTracker').distinct("Responsible Group", function(err, result)
{
//your code here
});

答案 1 :(得分:0)

mongodb docs中,您可以看到distinct返回null

  

distinct(key [,query] [,options],callback)

     

参数:

key (string) – key to run distinct against.
[query] (object) – option query to narrow the returned objects.
[options] (object) – additional options during update.
callback (function) – this will be called after executing this method. 
  The first parameter will contain the Error object if an error occured, or null otherwise. 
  While the second parameter will contain the results from distinct or null if an error occured.
     

**返回值:**

     

null

它将回调作为最后一个参数。在此回调中,第二个参数包含您要查找的结果。

因此您更新的代码如下:

function (callback) {
  db.collection('stgOmniTracker')
    .distinct("Responsible Group", function (err, group) {
        if (err) return callback(err);
        locals.group = group;
        callback();
    });
}