Skip to content
Advertisement

Function is not recognized in map reduce command, mongoDB (javascript)

I have some problems with a map reduce I tried to do in MongoDB. A function I defined seems to not be visible in the reduce function. This is my code:

function getName(user_id){
    var users = db.users.aggregate({$project:{"_id":"$_id", "name":"$name"}});        
    users.forEach((it) => {if (user_id == it._id) return it.name;});    
    return "user not found"; 
}
var mapFunc = function(){ emit(this.user_id, this.book_id) };
var reduceFunc = function(key, values){return getName(key);};
db.booksToRecover.mapReduce(mapFunc, reduceFunc, {out:'users_to_recover_books_from'});

This is what I get: ![enter image description here

Advertisement

Answer

The function was defined in the locally running javascript instance, not the server.

In order for that function to be callable from the server you will need to either predefine it there or include the definition inside the reduce function.

But don’t do that.

From the reduce function documentation:

The reduce function should not access the database, even to perform read operations.

Look at using aggregation with a $lookup stage instead.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement