Map Reduce in MongoDB: undefined is not a function
Problem
I have to use mapReduce
for a project and I started to follow the documentation.
I've created a test project following the first example from the page.
I've created a database named test
in Mongo, and I inserted the object from example in collection 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 } ]
}
My code is simple (like in example):
// 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
This throws this error:
.../node_modules/mongodb/lib/mongodb/connection/server.js:524
throw err;
^ TypeError: undefined is not a function
If I change to this, this error disappears.
collection.mapReduce(
mapFunction1,
reduceFunction1,
{ out: "col_two" },
function() {
// Print items from col_two
}
);
Why does the error disappear?
Solution
What you're hitting is one of the key differences between the API used in the shell and the native node.js driver: the shell is synchronous while the node.js driver is asynchronous.
Because the node.js driver is asynchronous, you must supply a callback parameter to the mapReduce
call as indicated in the documentation so that you can receive the result.
Discussion
View additional discussion.