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?

1
  • The /.../ syntax is only for strings, not variables. Many of the answers in the question you've linked provide your answer.
    – JohnnyHK
    Commented May 2, 2017 at 4:27

7 Answers 7

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);
5
  • 1
    Thanks for your answer. Above find is case-sensitive. how can I do this with case-insensitive? Commented Dec 3, 2017 at 12:28
  • 6
    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' } } Commented Apr 4, 2018 at 22:31
  • 2
    i is use for case insensitive Commented Apr 5, 2018 at 5:11
  • You can add options after the regex pattern as usual. /pattern/i Commented Aug 5, 2021 at 0:01
  • 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.
    – e-info128
    Commented May 24 at 19:40
31

Or just simply

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

i for case-insensitive

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

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()
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.