Search code examples
javascriptnode.jsmongodbapi-design

MongoDB : How can I reformat this code to include a sort on the name field?


How can I reformat this block in order to add sorting on the Name field?

   Router.route('/hospitals/search/:searchString')
      .get(function (req, res) {
        const searchString = decodeURIComponent(req.params.searchString)
        HospitalModel.find({
          $or: [
            {Name: {$regex: searchString, $options: 'i'}},
            {City: {$regex: searchString, $options: 'i'}}
          ]
        }, function (err, data) {
          const response = (err)
            ? {error: true, message: 'Server Error when querying hospitals collection.'}
            : {error: false, message: data}
          res.json(response)
        })
      })

I'm new to both mongo and API creation in general. The examples I've found don't really fit the way I've written this and I'm sort of lost at this point.


Solution

  • Try this code. Sorting can be done in different ways in mongoose.

    Following are the examples for that

    HospitalModel.find({}).sort('Name').exec(function(err, docs) { ... });
    HospitalModel.find({}).sort({Name: 1}).exec(function(err, docs) { ... });
    HospitalModel.find({}, null, {sort: {Name: 1}}, function(err, docs) { ... });
    HospitalModel.find({}, null, {sort: [['Name', -1]]}, function(err, docs) { ... }); 
    

    Generally what i follow is in this way. It will work for you too.

     Router.route('/hospitals/search/:searchString')
         .get(function(req, res) {
             const searchString = decodeURIComponent(req.params.searchString)
             HospitalModel.find({
                 $or: [
                     { Name: { $regex: searchString, $options: 'i' } },
                     { City: { $regex: searchString, $options: 'i' } }
                 ]
             }, null, { sort: { Name: 1 } }, function(err, data) {
                 const response = (err) ? { error: true, message: 'Server Error when querying hospitals collection.' } : { error: false, message: data }
                 res.json(response)
             })
         })