Mongoose.js: Find user by username LIKE value
Asked Answered
T

15

107

I like to to go find a user in mongoDb by looking for a user called value. The problem with:

username: 'peter'

is that i dont find it if the username is "Peter", or "PeTER".. or something like that.

So i want to do like sql

SELECT * FROM users WHERE username LIKE 'peter'

Hope you guys get what im askin for?

Short: 'field LIKE value' in mongoose.js/mongodb

Tern answered 22/3, 2012 at 14:12 Comment(1)
Just an aside, the SQL query wouldn't find Peter or PeTER either as LIKE is not case-insensitive.Lavone
T
167

For those that were looking for a solution here it is:

var name = 'Peter';
model.findOne({name: new RegExp('^'+name+'$', "i")}, function(err, doc) {
  //Do your action here..
});
Tern answered 29/3, 2012 at 19:52 Comment(8)
what does "i" argument mean? Does it have anything to do with case sensitivity?Kleenex
"i" is an argument for choosing a searching flag. "i" then is for case-insensitive. You can read more about it here. developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…Tern
This assumes the regex isn't invalid. If you add "[" as a username for example, will throw exception. Just ensure you are either try-catching or regexing your input prior and checking for [^a-zA-Z0-9] then not proceeding. In this case, its just test input so makes sense.Delirious
$ = Match the end of the stringTern
@JasonSebring Although I agree that input validation is not a bad idea, the best approach is an actual escaping algorithm. And exceptions are not even the worst problem, but imagine you used similar code on a login page and a user entered ".*" as the username.Thynne
@still_learning true. Do you know of one for this issue? I haven't thought much about it but it is necessary.Delirious
@still_learning found it here -> #3446670Delirious
{[nameOFFieldHere]: new RegExp([charSetForFindHere], "i")} This is a little bit improved string literal handling with [ ] and in new RegExp ( ) , it automatically added /charSetForFindHere/ pattern with / and / , which comes from inbuilt regex eg: {"firstName": /Bri/} Therefore use above like : {[fieldnameVariable]: new RegExp([searchStringChars], "i")} with variable field name and variable char set.Prather
T
83

I had problems with this recently, i use this code and work fine for me.

var data = 'Peter';

db.User.find({'name' : new RegExp(data, 'i')}, function(err, docs){
    cb(docs);
});

Use directly /Peter/i work, but i use '/'+data+'/i' and not work for me.

Tendency answered 22/3, 2012 at 14:52 Comment(2)
Well, i just tried it some more. I see it also find if i just write P?? hmmm.Tern
Yes, i use for ajax petitions to search users. You can modify the RegExp.Tendency
C
42
db.users.find( { 'username' : { '$regex' : req.body.keyWord, '$options' : 'i' } } )
Clinkstone answered 3/8, 2017 at 15:17 Comment(2)
@MikeShi What is an example scenario of this?Assignor
@LenJoseph just in general the ReDoS attack: owasp.org/index.php/…, I'm unaware if mongoose is vulnerable at this point, or if there is any intended functionality to detect ReDoS inputs and sanitize them at the mongoose level.Prime
R
16
collection.findOne({
    username: /peter/i
}, function (err, user) {
    assert(/peter/i.test(user.username))
})
Roofing answered 22/3, 2012 at 14:14 Comment(4)
what if the value is a var? How to set that up? /varhere/i ?Tern
@PeterBechP construct a regular expression :\ new RegExp(var, "i")Roofing
works fine.. now i got a problem.. It only have to find peter if the var is peter. But if i set the var to 'p' it will still find peter.Tern
@PeterBechP then remove the case insensitivity flag :\Roofing
O
15
router.route('/product/name/:name')
.get(function(req, res) {

    var regex = new RegExp(req.params.name, "i")
    ,   query = { description: regex };

    Product.find(query, function(err, products) {
        if (err) {
            res.json(err);
        }

        res.json(products);
    });

});  
Ollieollis answered 16/7, 2014 at 22:27 Comment(0)
O
13

You should use a regex for that.

db.users.find({name: /peter/i});

Be wary, though, that this query doesn't use index.

Organization answered 22/3, 2012 at 14:13 Comment(0)
S
9

mongoose doc for find. mongodb doc for regex.

var Person = mongoose.model('Person', yourSchema);
// find each person with a name contains 'Ghost'
Person.findOne({ "name" : { $regex: /Ghost/, $options: 'i' } },
    function (err, person) {
             if (err) return handleError(err);
             console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation);
});

Note the first argument we pass to mongoose.findOne function: { "name" : { $regex: /Ghost/, $options: 'i' } }, "name" is the field of the document you are searching, "Ghost" is the regular expression, "i" is for case insensitive match. Hope this will help you.

Scholiast answered 21/7, 2016 at 8:8 Comment(1)
what are the $optionsBayonne
H
9

The following query will find the documents with required string case insensitively and with global occurrence also

var name = 'Peter';
    db.User.find({name:{
                         $regex: new RegExp(name, "ig")
                     }
                },function(err, doc) {
                                     //Your code here...
              });
Hopscotch answered 28/11, 2016 at 6:4 Comment(0)
K
9

This is what I'm using.

module.exports.getBookByName = function(name,callback){
    var query = {
            name: {$regex : name}
    }
    User.find(query,callback);
}
Kashmiri answered 27/6, 2017 at 6:14 Comment(0)
Y
5

Here my code with expressJS:

router.route('/wordslike/:word')
    .get(function(request, response) {
            var word = request.params.word;       
            Word.find({'sentence' : new RegExp(word, 'i')}, function(err, words){
               if (err) {response.send(err);}
               response.json(words);
            });
         });
Yeargain answered 14/10, 2015 at 3:51 Comment(0)
S
2

Just complementing @PeterBechP 's answer.

Don't forget to scape the special chars. https://stackoverflow.com/a/6969486

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

var name = 'Peter+with+special+chars';

model.findOne({name: new RegExp('^'+escapeRegExp(name)+'$', "i")}, function(err, doc) {
  //Do your action here..
});
Soddy answered 13/9, 2019 at 16:18 Comment(0)
A
2

For dynamic search, you can follow like this also,

const { keyword, skip, limit, sort } = pagination(params);
const search = keyword
      ? {
          title: {
            $regex: new RegExp(keyword, 'i')
          }
        }
      : {};

Model.find(search)
      .sort(sort)
      .skip(skip)
      .limit(limit);
Appetizer answered 5/1, 2021 at 8:51 Comment(0)
C
1

if I want to query all record at some condition,I can use this:

if (userId == 'admin')
  userId = {'$regex': '.*.*'};
User.where('status', 1).where('creator', userId);
Cima answered 10/8, 2016 at 2:14 Comment(1)
Seems like an unnecessary use of $regex when you could have just used { $exists: true }.Ossetic
R
1

This is my solution for converting every value in a req.body to a mongoose LIKE param:

let superQ = {}

Object.entries({...req.body}).map((val, i, arr) => {
    superQ[val[0]] = { '$regex': val[1], '$options': 'i' }
})

User.find(superQ)
  .then(result => {
    res.send(result)})
  .catch(err => { 
    res.status(404).send({ msg: err }) })
Radioluminescence answered 13/8, 2020 at 5:58 Comment(0)
W
0
var name = 'Peter';

model.findOne({
  name: {
    $regex: name,
    $options: 'i'
  }, 
  function(err, doc) {
  //your logic
});

for more information you can refer this link https://www.mongodb.com/docs/manual/reference/operator/query/regex/

Wenn answered 16/8, 2022 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.