Shawn Varughese Shawn Varughese - 21 days ago 6
Node.js Question

Mongodb Query does not work with string

I am trying to get documents in the database that match the string but it does not work when i pass in the variable.

I have a string serviceString and serviceString = "test1", "test2", "test3"

query = db.collection('Services').find({
'Service': {
$in: [serviceString]
}
});


This returns nothing from the DB BUT if I do this:

query = db.collection('Services').find({
'Service': {
$in: ["test1", "test2", "test3"]
}
});


It works and returns what I need.

Do you know why its not working, I am thinking the string is putting commas in as a string. Whats a way I can do this because the string is a input from a user so it can change so I cant hard code the variables in the query?

Answer

$in is looking up for an array.

So, It's better to create an array of string you want to find.

let serviceString = ["test1", "test2", "test3"];

Note : You can also use var instead of let here

Then your query will look likes :

let serviceString = ["test1", "test2", "test3"];
query = db.collection('Services').find({
       'Service': {
           $in: serviceString
      }
});

more information : https://mongodb.github.io/node-mongodb-native/markdown-docs/queries.html#special-query-operators