Skip to main content

· One min read
John D. Johnson II

A cursor helps a server to find an item in a database.

If you're not exactly sure what that means here's an analogy. It's a lot like when you go to the library and have some information for a specific book. This information you have about the book can help you locate it.

A cursor (some information) can be turned into a database object (the book) by finding the first instance of it in the database (the library).

Below is a hypothetical example:

Cursor        -> Some query from a cursor -> DB Object
{name: "bob"} -> Some query from a cursor -> {name: "bob", job: "something", location: "some place 123rd street"}

An example of some query from a cursor, in MongoDB is:

const {name, job, location} = await Employee.findOne({name: "bob"});

A database object can be turned into a cursor with a transform of some sort in our case it will be provided by the user.

Below is a hypothetical example:

DB Object -> some transform to a cursor -> Cursor
{
name: "bob",
job: "something",
location: "some place 123rd street"
} -> some tranform to a cursor -> {name: "bob"}

· 2 min read
John D. Johnson II

TLDR; When should I choose cursoring?

When your new information is being added to the beggining of your sorted list that is returned from a database.

What are alternatives to cursor based paging?

Cursor based paging is sometimes just called cursoring so as not to confuse the term with regular non-cursor based paging.

From here on in this blog post I will use paging to refer to non-cursor based paging and cursoring to refer to cursor based paging.

If you don't know what cursoring is read more about cursoring here.

Paging generally uses skip and limit. Paging is usually displayed in individual pages and allows one to move from page to page with something like this:

Pagination Buttons

Whereas Cursoring is usually displayed in an infinite scrolling feed.

The problem with paging is say your pages of items are from newest to oldest, and that you store 20 items on each page. You (the user) are on page 2 and suddenly 20 new items are submitted to the beginning of the list of items. Suddenly now you're on page 3, but the UI still shows you on page 2, so when you click on page 3 nothing would appear to happen.

To avoid this problem we use cursoring. Which instead of keeping track of where you are based off a skip and limit, it keeps track of where you are based off of any single item in the collection and then allows you to ask for things before or after that item. Each single item in a collection can be turned into a cursor, so that you can query other items relative to where that item is in the collection.