Friday, 17 March 2017

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



via ronypatil

No comments:

Post a Comment