[SERVER-5385] MapReduce: when using scope with a function closures are broken Created: 23/Mar/12  Updated: 15/Aug/12  Resolved: 23/Mar/12

Status: Closed
Project: Core Server
Component/s: MapReduce
Affects Version/s: 2.1.0
Fix Version/s: None

Type: Bug Priority: Minor - P4
Reporter: Michael Coyne Assignee: Andy Schwerin
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Operating System: ALL
Participants:

 Description   

When using the "scope" option with a function that has formed a closure, the map function will break this closure and throw a ReferenceError when the supplied function is invoked.

This may be done intentionally... the docs are a bit sparse with regards to the "scope" option.

See the following:

test.js

> db.collection.save({})
 
> fn = function(){ var x = 1; return function(){ return x; }}()
function () {
    return x;
}
 
> fn()
1
 
> db.collection.mapReduce(function(){fn()}, function(){}, {out:'inline', scope:{fn:fn}})
Fri Mar 23 12:52:59 uncaught exception: map reduce failed:{
	"assertion" : "map invoke failed: JS Error: ReferenceError: x is not defined nofile_b:1",
	"assertionCode" : 9014,
	"errmsg" : "db assertion failure",
	"ok" : 0
}
> 



 Comments   
Comment by Michael Coyne [ 23/Mar/12 ]

Had written some code that created a date formatting function based upon some initial options. It's basic structure was:

test.js

var date_function = (function(){
	// build some vars here
	return function(){
		// use those vars here
	};
}());

Was able to still accomplish the flexible date formatting I need by passing in the "some built vars" through the scope option and moving the code that "used those vars" to the actual body of the map function.

Comment by Scott Hernandez (Inactive) [ 23/Mar/12 ]

See the docs for scope: http://www.mongodb.org/display/DOCS/Mapreduce#MapReduce-Overview

Comment by Andy Schwerin [ 23/Mar/12 ]

The scopes are read only in the map, reduce and finalize functions. Several instances of these functions might be executing simultaneously, on different machines or in different processes, and so mutating the variables in the scope can't be used in a predictable fashion.

Comment by Tad Marshall [ 23/Mar/12 ]

Re: code formatting ... just end your code with a bare "

{" code "}

" (paraphrased here to avoid having it executed), no slash at the beginning.

Comment by Michael Coyne [ 23/Mar/12 ]

total fail on the code formatting

Generated at Thu Feb 08 03:08:43 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.