TypeError:object不是使用MongoDB和Node.js的函数

我正在经历问题,并要求我计算每个class级孩子的最低分值。 我写了下面的源代码。
我使用的是Mongo 2.6.9和Node v0.10.25以及ubuntu 14.04 LTS

var MongoClient=require('mongodb').MongoClient; var server=require('mongodb').Server; var mongoclient=new MongoClient(new server("localhost",27017)); mongoclient.connect("mongodb://localhost:27017/",function(err,db){ if(err) throw err; var db=mongoclient.db('school'); cursor=db.collection('students').aggregate( [ {$match : {"scores.type" : "homework"}}, {$unwind:"$scores"}, {$group : {_id : '$name', 'minimum' : { $min :"$scores.score" } } } ]); }); 

使用节点app.js运行时,此聚合查询会产生此错误

 /home/oroborus/node_modules/mongodb/lib/mongodb/connection/base.js:246 throw message; ^ TypeError: object is not a function at /home/oroborus/node_modules/mongodb/lib/mongodb/collection/aggregation.js:317:7 at /home/oroborus/node_modules/mongodb/lib/mongodb/db.js:1195:7 at /home/oroborus/node_modules/mongodb/lib/mongodb/db.js:1903:9 at Server.Base._callHandler (/home/oroborus/node_modules/mongodb/lib/mongodb/connection/base.js:453:41) at /home/oroborus/node_modules/mongodb/lib/mongodb/connection/server.js:488:18 at MongoReply.parseBody (/home/oroborus/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5) at null.<anonymous> (/home/oroborus/node_modules/mongodb/lib/mongodb/connection/server.js:446:20) at EventEmitter.emit (events.js:95:17) at null.<anonymous> (/home/oroborus/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:207:13) at EventEmitter.emit (events.js:98:17) 

根据我来说这是来自聚合函数。 但是,当我在mongoterminal运行相同的查询,我得到一个正确的输出。

 cursor=db.students.aggregate( [ {$match : {"scores.type" : "homework"}}, {$unwind:"$scores"}, {$group : {_id : '$name', 'minimum' : { $min :"$scores.score" } } } ]); { "_id" : "Myrtle Wolfinger", "minimum" : 35.99397009906073 } { "_id" : "Gennie Ratner", "minimum" : 34.50565589246531 } { "_id" : "Nobuko Linzey", "minimum" : 19.27081566886746 } { "_id" : "Flora Duell", "minimum" : 40.68238966626067 } { "_id" : "Shin Allbright", "minimum" : 52.68629677727286 } 

问 – 什么,哪里是错误,如何纠正。
谢谢。

collection.aggregate()的最后一个参数需要是一个callback。 mongodb驱动程序期待函数,但最后一个参数是一个对象。 这就是为什么你得到这个错误。 这里是callback的修改后的代码:

 var MongoClient = require('mongodb').MongoClient; var server = require('mongodb').Server; var mongoclient = new MongoClient(new server("localhost", 27017)); mongoclient.connect("mongodb://localhost:27017/", function(err, db) { if (err) throw err; var db = mongoclient.db('school'); cursor = db.collection('students').aggregate( [ {$match: {"scores.type": "homework"}}, {$unwind: "$scores"}, { $group: { _id: '$name', 'minimum': {$min: "$scores.score"} } } ], function(err, result) { // callback console.dir(result); db.close(); } ); });