Mongoose.js: Find user by username LIKE value

Javascriptnode.jsMongodbFindMongoose

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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 6 - Javascript

You should use a regex for that.

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

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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

Solution 9 - Javascript

This is what I'm using.

module.exports.getBookByName = function(name,callback){
    var query = {
            name: {$regex : name}
    }
    User.find(query,callback);
}

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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

Solution 14 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontechbechView Question on Stackoverflow
Solution 1 - JavascripttechbechView Answer on Stackoverflow
Solution 2 - JavascriptDonflopezView Answer on Stackoverflow
Solution 3 - JavascriptKanomdookView Answer on Stackoverflow
Solution 4 - JavascriptRaynosView Answer on Stackoverflow
Solution 5 - JavascriptvictorkurauchiView Answer on Stackoverflow
Solution 6 - JavascriptSergio TulentsevView Answer on Stackoverflow
Solution 7 - JavascriptShashith DarshanaView Answer on Stackoverflow
Solution 8 - JavascriptprodeveloperView Answer on Stackoverflow
Solution 9 - JavascriptvikvincerView Answer on Stackoverflow
Solution 10 - JavascriptEnrico GiurinView Answer on Stackoverflow
Solution 11 - JavascriptfelipepastorelimaView Answer on Stackoverflow
Solution 12 - JavascriptAnil LoutombamView Answer on Stackoverflow
Solution 13 - JavascriptmaverickView Answer on Stackoverflow
Solution 14 - JavascriptSolomon BushView Answer on Stackoverflow