简体   繁体   中英

How to use query mongoose using a LIKE operator similar to that of SQL?

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.

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);
  }
);

Use RegExp Constructor

key: new RegExp(box),

Read More about RegExp

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/}
      ]
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM