2013-02-06 32 views
1

我必須使用mapReduce作爲一個項目,我開始關注documentationMongoDB中的地圖縮小:undefined不是函數

我已經創建了一個test project,它遵循頁面上的first示例。

我已經創建了一個名爲蒙戈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 
    } 
); 

爲什麼錯誤消失?

+1

因爲回調是'mapReduce'的必需參數。請參閱[文檔](http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#mapreduce)。 – JohnnyHK

+0

@JohnnyHK,他們爲什麼不使用[這裏]回調? –

+0

因爲這個例子使用的是一個同步接口的shell。 – JohnnyHK

回答

3

你碰到的是shell中使用的API和本地node.js驅動程序之間的主要區別之一:shell是同步的,而node.js驅動程序是異步的。

因爲Node.js的驅動程序是異步的,你必須按照documentation表示,這樣就可以得到結果提供一個回調參數爲mapReduce通話。