Search code examples
mongodbwhere-clauseloopback

build loopback where query dynamicaly


I'm trying to build the following query object dynamically

This code works with the hard coded object and returns data

var query = {where: {or: [{field1: /franklin/i}, {field2: /franklin/i}]}}
myMongoLoopbackModel.find(query,
     function(err, response) {
     if (err) cb(new Error('Something went wrong!'));
      cb(null, response);
   });

The query is trying to search mongodb, via the loopback api, where either field1 or field2 contain the string "franklin", and that string is provided by user input.

Here is the dynamic code that is not working.

var userinput= new RegExp(userform.inputvalue,'i');
var query= {where: []};
query['where'].push({or: [
    {field1: userinput},
    {field2: userinput}

 ]});
 myMongoLoopbackModel.find(query,
     function(err, response) {
     if (err) cb(new Error('Something went wrong!'));
      cb(null, response);
   });

When I console log the first, working, query i get:

log working:  { where: { or: [ [Object], [Object] ] } }

When I console log the second, non-working, query, I get:

log non-working: { where: [ { or: [Array] } ] }

I have researched other, similar, posts and derived my approach from this one. How to dynamically build MongoDB Query with multiple OR?

I would appreciate any help you can provide. Thank you.


Solution

  • where clause should not be an array. Rewriting your code:

    var userinput= new RegExp(userform.inputvalue,'i');
    var query = {where: {or: [{field1: userinput}, {field2: userinput}]}}
    myMongoLoopbackModel.find(query,
     function(err, response) {
     if (err) cb(new Error('Something went wrong!'));
      cb(null, response);
    });