【问题标题】:Map Reduce in MongoDB: undefined is not a functionMongoDB 中的 Map Reduce:未定义不是函数
【发布时间】:2013-02-07 02:13:23
【问题描述】:

我必须为一个项目使用mapReduce,我开始关注documentation

我按照页面中的first 示例创建了一个test project

我在 Mongo 中创建了一个名为 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
   }
);

为什么错误消失了?

【问题讨论】:

  • 因为回调是mapReduce的必填参数。见docs
  • @JohnnyHK,他们为什么不使用here 回调?
  • 因为该示例使用的是同步接口的 shell。
  • 测试过了。这是真的。如果您添加了一个很好的答案,我很高兴标记它。

标签: javascript node.js mongodb


【解决方案1】:

您遇到的问题是 shell 中使用的 API 与本机 node.js 驱动程序之间的主要区别之一:shell 是同步的,而 node.js 驱动程序是异步的。

因为 node.js 驱动是异步的,所以你必须提供一个回调参数给mapReduce 调用,如documentation 所示,这样你才能收到结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多