yozawiratama
yozawiratama

Reputation: 4328

How to query in mongodb programmatically?

I wannt to create code like this:

var result = Attributes.find({
    attribute_name : {
    $exist : true,
    $in : [1]
 }
});

but programmatically, so i ceate code like this:

var genQuery = '{ "' + by + '" : { "$exists" : true, "$in" : [' + data + ']} }';
var result = Attributes.find(genQuery);

but I get error maximum call stack

because result of JSON.parse(genQuery)

{ _id: { '$exists': true, '$in': [ 1 ] } }

How to query in mongodb programmatically?

Upvotes: 0

Views: 115

Answers (1)

255kb - Mockoon
255kb - Mockoon

Reputation: 6974

Your genQuery variable you declare is a String, but you cannot pass strings as selectors or modifiers in find() functions. You should create an Object to make it works:

var genQuery = {};
//use this notation to declare a new object key depending on a variable
genQuery[by] = {
  $exists: true, 
  $in: [1]
};

var result = Attributes.find(genQuery);

Upvotes: 1

Related Questions