51

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?

peterh
  • 11,875
  • 18
  • 85
  • 108
devnext
  • 872
  • 1
  • 10
  • 25
  • The /.../ syntax is only for strings, not variables. Many of the answers in the question you've linked provide your answer. – JohnnyHK May 02 '17 at 04:27

7 Answers7

87

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);
kumbhani bhavesh
  • 2,189
  • 1
  • 15
  • 26
28

Or just simply

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

i for case-insensitive

Nux
  • 5,890
  • 13
  • 48
  • 74
13

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);
};
zashishz
  • 377
  • 4
  • 6
9

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})
user3291025
  • 997
  • 13
  • 20
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()
sklimkovitch
  • 251
  • 4
  • 8
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.

Nolequen
  • 3,032
  • 6
  • 36
  • 55
Umer Baba
  • 285
  • 3
  • 4
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.

Erisan Olasheni
  • 2,395
  • 17
  • 20