Mongoose.js: Find user by username LIKE value

前端 未结 13 1414
梦毁少年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:37

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

提交回复
热议问题