0

I have a MongoDB query that works fine in console for getting partial matches across several fields:

db.Col.find({ "$or": [ { "product": /Su/}, { "location": /Su/ },{ "category": /Su/ } , { "owner": /Su/ }] })

I am using mongoose in my angular app and cannot figure out how to structure it to work. "filter" is the text coming in from my api call.

exports.listPartialMatches = function(req, res) {
  var filter = req.params.filter;
  Col.find().or([ { "project": /filter/ }, { "location": /filter/ },{ "location": /filter/ } , { "owner": /filter/ }]).exec(function(err, mycol) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(mycol);
    }
  });
};

For some reason the above returns an empty array, whereas the console command does not. I have also tried "/" + filter + "/" and /filter/i but they all come back empty.

Is there something wrong with the actually find() call here or is it something with the structure of my strings for the partial match?

Code2Code
  • 55
  • 7

1 Answers1

0

I didn't figure out how to use the /filter/ notation but this works:

exports.listPartialMatches = function(req, res) {
  var filter = req.params.filter;
  Col.find().or([ { "project": new RegExp(filter, "i") }, { "location": new RegExp(filter, "i") },{ "location": new RegExp(filter, "i") } , { "owner": new RegExp(filter, "i") }]).exec(function(err, mycol) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(mycol);
    }
  });
};

If anyone has a more elegant solution please share. This one seems a little messy but gets the job done.

Code2Code
  • 55
  • 7