ToArray undefined in NodeJS and MongoDB


I am trying to start aggregation of MongoDB and Nodejs, but I have some difficulties when starting the project. When I enter the following command in the MongoDB shell:

db.data.aggregate([{$match: {}},{$group: {'_id': '$State', 'total': {'$sum': 1}} }]).toArray() 

then I get the expected result.
However, when I use the following small Nodejs program

 var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/weather', function(err, db) { if(err) throw err; console.log("Connected correctly to server"); var col=db.collection('data'); col.aggregate([{$match: {}},{$group: {'_id': '$State', 'total': {'$sum': 1}} }]) .toArray(function(err, result) { if(err) throw err; console.log(result); }); db.close(); }); 

then I get an error: 'TypeError: Unable to read property' toArray 'from undefined'

Can someone please help me?

Thanks a lot in advance, Andi

+5
source share
2 answers

As @ExplosionPills correctly pointed out, your code will not work because logging is done asynchronously and after the connection is closed, so you can try to remove the db.close() or create a function that uses a callback function to return aggregation results:

 var aggregateStates = function(db, callback) { db.collection('data').aggregate( [ { $group: { "_id": "$State", "total": { $sum: 1 } } } ] ).toArray(function(err, result) { console.log(result); callback(result); }); }; 

Call the aggregateStates function:

 var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/weather', function(err, db) { aggregateStates(db, function() { db.close(); }); }); 
+1
source

According to the mongo-native driver doc , aggregate () returns null. Therefore, toArray () cannot be called from what it returns. However, aggregate () accepts the callback, which has the result of aggregate () if successful. So here is the redesigned code:

 var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost:27017/weather', function(err, db) { if(err) throw err; console.log("Connected correctly to server"); var col=db.collection('data'); col.aggregate([ {$match: {}}, {$group: {'_id': '$State', 'total': {'$sum': 1}} } ], function(err, result) { if(err) { db.close(); throw err; } console.log(result); db.close(); }); }); 
+1
source

All Articles