Reputation: 131
I am trying to query my database to search for products based on name and category. I want the database to return an array of products when a user searches for something, this string should match either the category of the procut or the type or the name. I am doing the following
Product.find(
{
$or: [
{
name: /box/,
type: /box/,},
],
},
function (err, results) {
console.log(err);
console.log(results);
}
);
I am not able to use my variable box in:
name: /box/
I have tried "/" + box + "/" and putting my variable in // when creating it but none of that is working.
How do I use like operator to query my db.
Upvotes: 0
Views: 822
Reputation: 2011
Looks like there is a mistake in the $or
operator syntax also. Each expression should be separate curly brackets. Also since you are using mongoose you can use the regex as below. $option is used to make the search case insensitive.
Product.find(
{
$or: [
{
name: { $regex: "box", $options: "i" },
},
{ type: { $regex: "box", $options: "i" } },
],
},
function (err, results) {
console.log(err);
console.log(results);
}
);
Upvotes: 1
Reputation: 937
I think what you're trying to do is making use of $or operator. Syntax is like this:
Product.find(
{
$or: [
{name: /box/},
{type: /box/}
]
});
Upvotes: 0