在MongoDB中缩小地图:undefined不是一个函数

我必须为项目使用mapReduce ,并开始遵循文档 。

我已经在页面的第一个例子之后创build了一个testing项目 。

我已经在Mongo中创build了一个名为test的数据库,并且我将这个例子中的对象插入到col_one集合中:

 { _id: ObjectId("50a8240b927d5d8b5891743c"), cust_id: "abc123", ord_date: new Date("Oct 04, 2012"), status: 'A', price: 250, items: [ { sku: "mmm", qty: 5, price: 2.5 }, { sku: "nnn", qty: 5, price: 2.5 } ] } 

我的代码很简单(例如):

 // MongoDB part // Create server var mapFunction1 = function() { emit(this.cust_id, this.price); }; var reduceFunction1 = function(keyCustId, valuesPrices) { return Array.sum(valuesPrices); }; collection.mapReduce( mapFunction1, reduceFunction1, { out: "col_two" } ); // Print items from col_two 

这会引发这个错误:

 .../node_modules/mongodb/lib/mongodb/connection/server.js:524 throw err; ^ TypeError: undefined is not a function 

如果我改变这个,这个错误消失。

 collection.mapReduce( mapFunction1, reduceFunction1, { out: "col_two" }, function() { // Print items from col_two } ); 

为什么错误消失?

您所碰到的是shell中使用的API和本地node.js驱动程序之间的主要区别之一:shell是同步的,而node.js驱动程序是asynchronous的。

由于node.js驱动程序是asynchronous的,因此您必须按照文档中的说明为mapReduce调用提供一个callback参数,以便您可以接收结果。