Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to do ajax pagination with MongoDb and Nodejs?

I have mongodb and NodeJs. The connection is done via mongoosejs.
What is the best way to develop ajax infinity scroll ? Should I use limit and offset ?

like image 232
Oleg Dats Avatar asked Apr 09 '12 11:04

Oleg Dats


People also ask

Can Ajax be used in Node JS?

This can be done by Ajax request, we are sending data to our node server, and it also gives back data in response to our Ajax request. Step 1: Initialize the node modules and create the package. json file using the following command.

What is pagination NodeJS?

Pagination in NodeJS is defined as adding the numbers to identify the sequential number of the pages. In pagination, we used to skip and limit for reducing the size of data in the database when they are very large in numbers. In this article, we will do pagination in NodeJS using sorting IDs.

What is pagination in Ajax?

Pagination in Web Application is one of the required feature for load data on web page, in which include load large number of data from database. The main benefit of Pagination is the load dynamic data faster because it has divided data loading process in multiple pages.


1 Answers

"skip and limit" approach is not very efficient when you are paging far into dataset. It is effectively a Shlemiel the Painter's algorithm.

Range queries are much more efficient (when supported by indexes). For example, let's imagine that you're displaying tweets. Your page size is 20 and you're on page 1000 and want to load page 1001.

This query

db.tweets.find().sort({created_at: -1}).skip(1001*20).limit(20)

is much less efficient than

db.tweets.find({created_at: {$lt: last_displayed_date}}).
          sort({created_at: -1}).limit(20);

(provided that you have index on created_at).

You get the idea: when you load a page, note the timestamp of the last tweet and use it to query the next page.

like image 106
Sergio Tulentsev Avatar answered Sep 19 '22 19:09

Sergio Tulentsev