簡體   English   中英

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

[英]MongoDB : How can I reformat this code to include a sort 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)
        })
      })

我對mongo和API創建都是新手。 我發現的示例與我撰寫本文的方式並不完全相符,在這一點上我有些迷失。

試試這個代碼。 可以用貓鼬的不同方式進行排序。

以下是該示例

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

通常我遵循的就是這種方式。 它也會為您服務。

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

試試下面的代碼

       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