How I can use "LIKE" operator on mongoose?
Asked Answered
N

7

53

I have a problem when i query using mongoose.I coding follow this Mongoose.js: Find user by username LIKE value. But it return blank.

This my code return blank.

 var promise = UserSchema.find({name: /req.params.keyword/ }).limit(5);

I tried this return blank seem.

var n = john; var promise = UserSchema.find({name: /n/ }).limit(5);

But i tried this is working

 var promise = UserSchema.find({name: /john/ }).limit(5);

Why I use variable then return blank?

Nelson answered 2/5, 2017 at 2:36 Comment(1)
The /.../ syntax is only for strings, not variables. Many of the answers in the question you've linked provide your answer.Barrick
I
90

use $regex in mongodb

how to use regex

example

select * from table where abc like %v%

in mongo

 var colName="v";
 models.customer.find({ "abc": { $regex: '.*' + colName + '.*' } },
   function(err,data){
         console.log('data',data);
  });

Your query look like

var name="john";
UserSchema.find({name: { $regex: '.*' + name + '.*' } }).limit(5);
Immediacy answered 2/5, 2017 at 4:17 Comment(5)
Thanks for your answer. Above find is case-sensitive. how can I do this with case-insensitive?Gui
Have you read a documentation how to use regex? you need to use { <field>: { $regex: 'pattern', $options: '<options>' } } with options i, e.g. { name: { $regex: req.params.keyword, $options: 'i' } }Cas
i is use for case insensitiveImmediacy
You can add options after the regex pattern as usual. /pattern/iConstantia
This have a Regex injection vulnerability and can cause uncontrolled use of memory and CPU resources and cause a denial of service. You need to escape the variable before using it in the query.Flamboyant
C
31

Or just simply

const name = "John"
UserSchema.find({name: {$regex: name, $options: 'i'}}).limit(5);

i for case-insensitive

Convergent answered 4/4, 2019 at 10:57 Comment(0)
G
14

This is how i have done it to find if search string present in name/email. Hope it helps someone.

const getPeerSuggestions = async (req, res, next) => {

  const { search } = req.query;
  const rgx = (pattern) => new RegExp(`.*${pattern}.*`);
  const searchRgx = rgx(search);

  const peers = await User.find({
    $or: [
      { name: { $regex: searchRgx, $options: "i" } },
      { email: { $regex: searchRgx, $options: "i" } },
    ],
  })
    .limit(5)
    .catch(next);

  res.json(peers);
};
Gallic answered 15/6, 2020 at 9:5 Comment(0)
U
10

You can use the RegExp object to make a regex with a variable, add the 'i' flag if you want the search to be case insensitive.

const mongoose = require('mongoose');
const User = mongoose.model('user');

const userRegex = new RegExp(userNameVariable, 'i')
return User.find({name: userRegex})
Ulmer answered 27/10, 2018 at 22:55 Comment(0)
K
1

Without aggregate it didn't work for me. But this did:

db.dbname.aggregate([{ "$match" : {"name" : { $regex: '.*SERGE.*', $options: 'i' } }}, { $sort: { "createdTime" : -1 }} ]).pretty()
Kishakishinev answered 23/2, 2021 at 15:23 Comment(0)
B
1
 select * from table where abc like %_keyword%

in mongo it is

  const list = await ProductModel.find({{ pname :{ $regex : '.*'+ _keyword + '.*' }});

here _keyword can be any text eg. fruit, pen, etc. as i am searching products model.

Battleship answered 3/11, 2021 at 11:29 Comment(0)
C
0

You can run a regex lookup with dynamic values using RegExp:

 var promise = UserSchema.find({name: new RegExp(req.params.keyword, 'i') }).limit(5);

Notice the 'i' option for case insensitivity.

Constantia answered 5/8, 2021 at 0:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.