I'm kind of confused on how to use closures in mongodb shell.
I want to create a function that i can use exclusively during development to quickly look up a document by a part of it's _id
.
The function should return a $where
selector that does the necessary matching.
I wanted to write it like this:
var id = function(pattern, selector) {
return Object.extend({
$where: function() {return (this._id + "").indexOf(pattern) != -1;}
}, selector);
};
But when i try it i get the following error:
db.mycollection.find(id("ab1"));
error: {
"$err" : "JavaScript execution failed: ReferenceError: pattern is not defined near ').indexOf(pattern) ' ",
"code" : 16722
}
Invoking $where
manually does seem to work oddly enough:
id("ell").$where.call({_id: "hello"}); // true
I could only think of this as a solution to make it work, but this is obviously terrible.
To clarify: This method with new Function
works fine, but i don't like it as the above method should work as well.
var id = function(pattern, selector){
return Object.extend({
$where: new Function("return (this._id + '').indexOf('" + pattern + "') != -1;")
}, selector);
};
- Why is my closure not working, do closures work in mongodb shell ?
- Bonus question: Can i register this function somewhere in a user profile to load automatically ?