5

How can I do a like query in MongoDB using Node.js?

Here's my source code, but it doesn't work:

exports.findAll = function(req, res) {
    var country=req.params.country; 
    db.collection('wines', function(err, collection) {
        collection.find({ 'country': new RegExp('/'+country+'/i') }).toArray(function(err, items) {
            res.jsonp(items);
        });
    });
};
3

1 Answer 1

17

I solved it like this:

 exports.findAll = function(req, res) {
        var country=req.params.country; 
        db.collection('wines', function(err, collection) {
            collection.find({ 'country': new RegExp(country, 'i') }).toArray(function(err, items) {
                res.jsonp(items);
            });
        });
    };
Sign up to request clarification or add additional context in comments.

4 Comments

how to use this find regex in dynamic key? ex : var key = request.body.key; find({ key : new RegExp(country, 'i') }); I've tried this but still the key is considered not as string
what is 'i' in this?
case insensitive search
If we want to apply on mongoose _id then this "new RegExp(req.query.search, 'i');" not work. Anybody know how to solve this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.