1

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?

4
  • 1
    Because the callback is a required parameter of mapReduce. See docs. Commented Feb 6, 2013 at 17:59
  • @JohnnyHK, Why didn't they use here the callback? Commented Feb 6, 2013 at 18:02
  • Because that example is using the shell which is a synchronous interface. Commented Feb 6, 2013 at 18:03
  • Tested it. It's true. If you add a great answer, I am glad to mark it. Commented Feb 6, 2013 at 18:09

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.