Reputation: 393
I've a little problem with my script. I cannot passing a parameter (MYPARAMETER in the example) in the function in the '$where'.
You have an idea for help me ? Thanks.
var MYPARAMETER = "dqsd qsdqs &é&é";
MyCol.findOne({
$where: function(MYPARAMETER)
{
var tab1="ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ!#$€%&'`(),;:/@.*[]\|";
var tab2= "aaaaaaaaaaaaooooooooooooeeeeeeeecciiiiiiiiuuuuuuuuynn ";
rep2=tab1.split('');
rep=tab2.split('');
parray=new Array();
var i=-1;
while(rep2[++i])
{
parray[rep2[i]]=rep[i]
}
var chaine = this.name.replace(/\s{1,}/g,"-");
chaine = chaine.replace(/./g, function($0){return (parray[$0])?parray[$0]:$0 });
chaine = chaine.replace(/\s/g,"");
return (chaine == MYPARAMETER);
}
},
Upvotes: 2
Views: 5350
Reputation: 602
Use the $where operator to pass either a string containing a JavaScript expression or a full JavaScript function to the query system.
To pass a variable just create a string containing your local data like this (You don't need to parse it):
const myLocalVar = "test"
const $where = `function() {
return this.template.indexOf('${myLocalVar}')>=0
}`
db.collection.find({$where})
Upvotes: 0
Reputation: 97
To use variables in $where query, first create mongo query as a string and then parse string to JSON when passing as parameter
Example:
var query = '{"$where": "function() { return (\'' + address + '\').indexOf(this.city) >= 0 }"}';
db.city.find(JSON.parse(query);
Upvotes: 1
Reputation: 113
This one is works for me , Just try to store a query as a string in one variable then concat your variable in query string,
var local_var = 42
var query = "{$where: function() { return this.a == "+local_var+"}}"
db.test.find(query)
Upvotes: 0
Reputation: 59763
A $where
executes on the server, and thus wouldn't have access to a variable that was locally declared on another server. JavaScript should be used as a last resort generally in MongoDB, and this appears to go the other way and perform a LOT of very time consuming work.
You'd need to build the function as a string and include the value directly.
Upvotes: 3