Mongoose.js: Find user by username LIKE value

138,455

Solution 1

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

Solution 2

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.

Solution 3

db.users.find( { 'username' : { '$regex' : req.body.keyWord, '$options' : 'i' } } )

Solution 4

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

});  

Solution 5

collection.findOne({
    username: /peter/i
}, function (err, user) {
    assert(/peter/i.test(user.username))
})
Share:
138,455

Related videos on Youtube

techbech
Author by

techbech

Updated on January 05, 2021

Comments

  • techbech
    techbech over 3 years

    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

    • beny23
      beny23 over 12 years
      Just an aside, the SQL query wouldn't find Peter or PeTER either as LIKE is not case-insensitive.
  • techbech
    techbech over 12 years
    what if the value is a var? How to set that up? /varhere/i ?
  • Raynos
    Raynos over 12 years
    @PeterBechP construct a regular expression :\ new RegExp(var, "i")
  • techbech
    techbech over 12 years
    Well, i just tried it some more. I see it also find if i just write P?? hmmm.
  • techbech
    techbech over 12 years
    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.
  • Donflopez
    Donflopez over 12 years
    Yes, i use for ajax petitions to search users. You can modify the RegExp.
  • Raynos
    Raynos over 12 years
    @PeterBechP then remove the case insensitivity flag :\
  • AzaFromKaza
    AzaFromKaza almost 11 years
    what does "i" argument mean? Does it have anything to do with case sensitivity?
  • techbech
    techbech almost 11 years
    "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/…
  • King Friday
    King Friday over 10 years
    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.
  • techbech
    techbech about 10 years
    $ = Match the end of the string
  • Tobias
    Tobias over 9 years
    @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.
  • King Friday
    King Friday over 9 years
    @still_learning true. Do you know of one for this issue? I haven't thought much about it but it is necessary.
  • King Friday
    King Friday over 9 years
    @still_learning found it here -> stackoverflow.com/questions/3446170/…
  • kabuto178
    kabuto178 over 6 years
    what are the $options
  • Len Joseph
    Len Joseph about 5 years
    @MikeShi What is an example scenario of this?
  • Mike Shi
    Mike Shi about 5 years
    @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.
  • sean
    sean over 4 years
    Seems like an unnecessary use of $regex when you could have just used { $exists: true }.
  • Rakshitha Muranga Rodrigo
    Rakshitha Muranga Rodrigo over 3 years
    {[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.