0

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

2 Answers 2

2
Entry.find({}).sort({ "_id" : -1 }).limit(100).exec(function(err, entries) {
    // Do something here
});
Sign up to request clarification or add additional context in comments.

1 Comment

This is not loading any data.
1

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

2 Comments

thats bad. you still load unnecessary the whole collection just to slice the last 100
Appearently this is the only working solution so far but is @Ifaruki mentioned i dont want to load whole data and slice it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.