Mongoose.js: Find user by username LIKE value

前端 未结 13 1363
梦毁少年i
梦毁少年i 2020-11-27 10:48

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

相关标签:
13条回答
  • 2020-11-27 11:43

    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..
    });
    
    0 讨论(0)
  • 2020-11-27 11:43
    db.users.find( { 'username' : { '$regex' : req.body.keyWord, '$options' : 'i' } } )
    
    0 讨论(0)
  • 2020-11-27 11:44

    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.

    0 讨论(0)
  • 2020-11-27 11:45

    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);
    
    0 讨论(0)
  • 2020-11-27 11:46

    You should use a regex for that.

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

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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题