简体   繁体   中英

List last N record from MongoDB collection

I have below route in my 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
      });
    }
  });
});

This is displaying all entries in Entry collection. I would like to display only last 100 records from db. What is the best way to do it?

I am using with below pug layout.

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

You could also use javascript to only send the last 100 items to the Pug layout:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM