Home > Mobile >  formulating the right object to call mongodb find() in nodejs
formulating the right object to call mongodb find() in nodejs

Time:08-09

I am new to nodejs, I am trying to create a Mongodb find() query, that should look like this ...

{$and: [{search_text: {$regex: /foo/ }}, {search_text: {$regex: /BAR/ }}]}

I am running a script that builds that query from input, but I am getting messed up somewhere as it complains like ...

Cast to Object failed for value "{search_text: {$regex: '/foo/'}}" (type string) at path "$and.0" for model "textSearch"

the code that generates the "Object"? ....

  let search_query = ["foo", "BAR"] // assumed User Input
  console.log("ORIG QUERY", search_query, search_query.length);
  let arg_group = [];
  let arg_template = [];
  let arg_object = {}
  for (i in search_query){
    arg_query = "{search_text: {$regex: '/"   String(search_query[i])   "/'}}"
    // arg_query = {'search_text': search_query[i]}
    arg_group = arg_group.concat(arg_query)
    console.log("ARG_QUERY", arg_group)
  }
  console.log("GROUP_QUERY", arg_group)
  arg_template = arg_template.concat(arg_group)
  console.log("TEMPLATE", arg_template)
  arg_object['$and'] = arg_template
  console.log("OBJECT", arg_object)

The output from the last console.log() is ...

OBJECT {
  '$and': [
    "{search_text: {$regex: '/foo/'}}",
    "{search_text: {$regex: '/BAR/'}}"
  ]
}

So it looks like I am munging strings and dictionaries together badly, but before I get better at that, is this even the right way to capture this input and form it into a query

CodePudding user response:

arg_query needs to be an object instead of string, like this:

arg_query = {search_text: { $regex: new RegExp(search_query[i]) }}

The new RegExp is how you convert an existing variable into a regular expression.

But you can simplify your query a bit with the $in operator and could replace your for loop with:

arg_group = [{
    search_text: { $in: search_query.map(q => new RegExp(q)) }
}]

map takes each value in an array and let's you return a different (or the same) value.

  • Related