Search code examples
mongodbangularmongoosemean-stack

How to create like %keyword% query in MongoDB using Nodejs


I am working on a MEAN application and want to implement a search filter. I am passing the search keyword in below route as follows

router.route("/places/search/:keyword")
    .get(function (req, res) {

        query = {};
        if (req.params.keyword !== undefined) {
            query = {
                name: { '$regex': new RegExp("^" + req.params.keyword.toLowerCase(), "i") }
            };
        }
        var response = {};
        Place.find(query, function (err, data) {
            if (err) {
                response = { "error": true, "message": "Error fetching data" };
            } else {
                response = { "error": false, "message": data };
            }
            res.json(response);
        });
    });

Above code is doing search like keyword% that returns all places having name starting with the passed keyword but I want to fetch all places where name contains keyword either in start, middle or at the end, something like %keyword% in MySQL.


Solution

  • router.route("/places/search/:keyword")
        .get(function (req, res) {
    
            query = {};
            if (req.params.keyword !== undefined) {
                query = {
                    name: new RegExp(req.params.keyword, 'i')
                };
            }
            var response = {};
            Place.find(query, function (err, data) {
                if (err) {
                    response = { "error": true, "message": "Error fetching data" };
                } else {
                    response = { "error": false, "message": data };
                }
                res.json(response);
            });
        });