简体   繁体   English

MongoDB:如何重新格式化此代码以在名称字段上包括排序?

[英]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. 我对mongo和API创建都是新手。 The examples I've found don't really fit the way I've written this and I'm sort of lost at this point. 我发现的示例与我撰写本文的方式并不完全相符,在这一点上我有些迷失。

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

Try below code 试试下面的代码

       HospitalModel.find(
     $or: [{
       Name: {
         $regex: searchString,`
         $options: 'i'
       }
     }, {
       City: {
         $regex: searchString,
         $options: 'i'
       }
     }]
   ) .sort({
       Name: 1
     }).exec(function(err, data) {
       const response = (err) ? {
         error: true,
         message: 'Server Error when querying hospitals collection.'
       } : {
         error: false,
         message: data
       }

       return res.json(response);
     });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM