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
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..
});
db.users.find( { 'username' : { '$regex' : req.body.keyWord, '$options' : 'i' } } )
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.
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);
You should use a regex for that.
db.users.find({name: /peter/i});
Be wary, though, that this query doesn't use index.
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.