2016-08-22 5 views
0

[名前]フィールドに並べ替えを追加するには、このブロックをどのように再フォーマットできますか?MongoDB:名前フィールドにソートを含めるには、このコードをどのように再フォーマットできますか?

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作成の両方に新しいです。私が見つけた例は、私がこれを書いたやり方に本当に適合していないし、私はこの時点で一種の失われている。

答えて

3

このコードを試してください。マングースではさまざまな方法でソートを行うことができます。続き

はその

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

の下に試してみてくださいありがとうございました。魅力のように動作します。私は例を感謝します。 –

0

コード

 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); 
    }); 
関連する問題