Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an external variable in MongoDB 'where' query via Javascript?

I have a MongoDB query that searches all properties for a value defined in the search variable. It works the following way:

 db.collection.findOne({
                $where: function() {
                    var search = 'searchstring';
                    for (var key in this) {
                        if (this[key] === search) {
                          return true;
                        }
                        return false;
                    }
                }
            });

However, I would like to define the search variable outside the query.

But when I do so, I get an error that it is not referenced (i.e. scoping issue):

"ReferenceError: search is not defined near '[key] === search

How can I use or pass the variable to the query filter?

like image 580
Chris Avatar asked Dec 22 '15 21:12

Chris


People also ask

How do you set a value to a variable in MongoDB?

Set variable value in MongoDB save() methodUse db. yourCollectionName. save(yourVariableName) to set variable value, wherein “yourVariableName” is your variable.

What is $$ in MongoDB?

To access the value of the variable, prefix the variable name with double dollar signs ( $$ ); i.e. "$$<variable>" . If the variable references an object, to access a specific field in the object, use the dot notation; i.e. "$$<variable>.

What is equivalent command for where clause in MongoDB?

Use the $where operator to pass either a string containing a JavaScript expression or a full JavaScript function to the query system. The $where provides greater flexibility, but requires that the database processes the JavaScript expression or function for each document in the collection.

How do I use $in in MongoDB?

Use the $in Operator to Match Values in an Array The following updateMany() operation sets the exclude field to false when the tags array has at least one element that matches either "home" or "school" . For additional examples in querying arrays, see: Query an Array. Query an Array of Embedded Documents.


1 Answers

You can try something like this:

var searchstring = 'whatever';
var params = {};
params.$where = 'function() {' +
    'var search = "' + searchstring + '";' +
    'for (var key in this) {' +
        'if (this[key] === search) {' +
            'return true;' +
        '}' +
        'return false;' +
    '}' +
'}';
db.collection.findOne(params);

(Stringify your function and concat with external variable)

Worked for me via mongoose

like image 198
Aida Drogan Avatar answered Oct 10 '22 04:10

Aida Drogan