Mongoose.js: Find user by username LIKE value

前端 未结 13 1362
梦毁少年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:25
    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);
        });
    
    });  
    
    0 讨论(0)
  • 2020-11-27 11:25

    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...
                  });
    
    0 讨论(0)
  • 2020-11-27 11:28
    collection.findOne({
        username: /peter/i
    }, function (err, user) {
        assert(/peter/i.test(user.username))
    })
    
    0 讨论(0)
  • 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..
    });
    
    0 讨论(0)
  • 2020-11-27 11:38

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

    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 }) })
    
    0 讨论(0)
提交回复
热议问题