Mongooseでは、日付で並べ替えるにはどうすればよいですか? (node.js)

StackOverflow https://stackoverflow.com/questions/5825520

  •  26-10-2019
  •  | 
  •  

質問

このクエリをMongooseで実行したとしましょう。

Room.find({}, function(err,docs){

}).sort({date:-1}); 

これはうまくいきません!

役に立ちましたか?

解決

ソート Mongooseでは、これらの回答のいくつかがもはや有効ではなくなるようにリリースを介して進化しました。のように 4.1.x Mongooseのリリース、上の下降ソート date フィールドは、次のいずれかの方法で実行できます。

Room.find({}).sort('-date').exec(function(err, docs) { ... });
Room.find({}).sort({date: -1}).exec(function(err, docs) { ... });
Room.find({}).sort({date: 'desc'}).exec(function(err, docs) { ... });
Room.find({}).sort({date: 'descending'}).exec(function(err, docs) { ... });
Room.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Room.find({}, null, {sort: '-date'}, function(err, docs) { ... });
Room.find({}, null, {sort: {date: -1}}, function(err, docs) { ... });

昇順の場合は、省略します - 文字列バージョンのプレフィックスまたはの値を使用します 1, asc, 、 また ascending.

他のヒント

正解は次のとおりです。

Blah.find({}).sort({date: -1}).execFind(function(err,docs){

});

Mongoose 3.5(.2)を使用して今日この問題に対処してきましたが、この問題を解決するのに役立ちませんでした。次のコードスニペットがトリックを行います

Post.find().sort('-posted').find(function (err, posts) {
    // user posts array
});

必要な標準パラメーターを送信できます find() (例えば、条項と返品フィールド)が 番号 折り返し電話。コールバックがなければ、あなたがチェーンするクエリオブジェクトを返します sort() の上。あなたは電話する必要があります find() 繰り返しますが、(パラメーターの多くの有無にかかわらず - 効率的な理由で必要ないはずです)、結果をコールバックに設定できるようになります。

私はこれをします:

Data.find( { $query: { user: req.user }, $orderby: { dateAdded: -1 } } function ( results ) {
    ...
})

これは、最新のものを最初に示します。

Post.find().sort({date:-1}, function(err, posts){
});

同様に機能するはずです

編集:

エラーが発生した場合は、これを使用することもできます sort() only takes 1 Argument :

Post.find({}, {
    '_id': 0,    // select keys to return here
}, {sort: '-date'}, function(err, posts) {
    // use it here
});

これが役立つかどうかを確認します> マングースで並べ替える方法は?

これも読んでください> http://www.mongodb.org/display/docs/sorting++natural+order

短い解決策:

const query = {}
const projection = {}
const options = { sort: { id: 1 }, limit: 2, skip: 10 }

Room.find(query, projection, options).exec(function(err, docs) { ... });
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top