从MongoDB集合中列出最后的N条记录

问题描述 投票:0回答:1

我有以下 route 在我 app.js

// Home Route
app.get('/', function(req, res){
  Entry.find({}, function(err, entries){
    if(err){
      console.log(err);
    } else {
      res.render('index', {
        entries: entries
      });
    }
  });
});

这是在显示 所有条目 在条目集合中。我想从db中只显示最后100条记录。什么是最好的方法来做到这一点?

我使用下面的 pug 布局。

extends layout
    block content
      h1 #{title}
      ul.list-group
        each entry, i in entries
          li.list-group-item
            a(href=entry.entryurl)= entry.title
node.js mongodb pug
1个回答
2
投票
Entry.find({}).sort({ "_id" : -1 }).limit(100).exec(function(err, entries) {
    // Do something here
});

1
投票

你也可以使用javascript只发送最后100个项目到Pug布局。

// Home Route
app.get('/', function(req, res){
  Entry.find({}, function(err, entries){
    if(err){
      console.log(err);
    } else {
      let lastHundred = entries.slice(-100);
      res.render('index', {
        entries: lastHundred
      });
    }
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.