teja teja - 3 months ago 21
Node.js Question

How can i sort in mongoDB query?

Iam new to mongoDB . Please anyone help me in writing mongoose query for sorting a particular feild???

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

Answer

Please try this will work for you.

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