Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node Express Mongoose : writing API to search data by multiple optional params

I have one search input box and user should be able to search by either employee id or firstname or last name. Employee id is also a string. I have mongo model called profile which has employee info.

I'm using node Express and mongoose. I would like to have a router that receive id or firstname or lastname as request param as below.

     this.router.get('/name/:name', this.getMidSearchResults);

private getMidSearchResults(req: Request, res: Response, next: NextFunction)         {
   var nameRegex = {"$regex": new RegExp('^' + req.params.name.toLowerCase(),  'i')};

   Profile.find({ mid: nameRegex } || {firstName: nameRegex} || {lastName: nameRegex}, function(err,   data) {
        if (err) throw err;
        res.send(data);
    });
  }
like image 417
ronypatil Avatar asked Oct 18 '25 08:10

ronypatil


1 Answers

Instead of:

Profile.find({ mid: nameRegex } ||
             { firstName: nameRegex } ||
             { lastName: nameRegex }, function (err, data) {
    // ...
});

use:

Profile.find({$or: [
    { mid: nameRegex },
    { firstName: nameRegex },
    { lastName: nameRegex }
]}, function (err, data) {
    // ...
});
like image 181
rsp Avatar answered Oct 19 '25 21:10

rsp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!