I am trying to run an aggregation MongoDB and Nodejs, but I have some difficulties in running 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 am getting the expected output.
However, when I use the following little 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 am getting the error message: 'TypeError: Cannot read property 'toArray' of undefined'
Could somebody please help me?
Many thanks in advance, Andi
cannot read propertyerror but it won't work because the reading is done asynchronously and after the connection is closed. Try removing thedb.closeline.