LoginSignup
22
26

More than 5 years have passed since last update.

Node.jsからMongoDBのソートや件数指定

Posted at

なかなか上手く行かなかったのでメモです.

Mongooseを使ってNode.jsからMongoDBのソートや件数の指定をするにはこんな感じで書けば良いみたいです。

モデル名.find(検索条件,カラム指定(?),オプション, function(err, data){
    //ここに処理
});

具体例

idがsampleのドキュメントを全フィールドを取得して,最新の2件を取得する

index.js
var query = { "id": "sample" };
Post.find(query,{},{sort:{created: -1},limit:2}, function(err, data){
        if(err){
            console.log(err);
        }
        res.render('index', {data: data});
    });

これでdataの中身は投稿されたものの最新の2件になってると思います。

22
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
26