Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose.js: Find user by username LIKE value

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

like image 233
techbech Avatar asked Mar 22 '12 14:03

techbech


People also ask

Can I use $in in mongoose?

For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator. In this article, we will discuss how to use $in operator. We will use the $in method on the kennel collection.

What does find by id return mongoose?

findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .

What is __ V in MongoDB?

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero ( __v:0 ).


2 Answers

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.. }); 
like image 111
techbech Avatar answered Sep 19 '22 12:09

techbech


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.

like image 35
Donflopez Avatar answered Sep 18 '22 12:09

Donflopez