I struggled to find a simple example of how I could return paginated results from an Azure CosmosDB from a Node.js Express application. Luckily, I eventually came across a brilliant article by Elio Struyf which can be found here – Retrieving the CosmosDB query continuation token in Node.js.
I’ll post my complete example of pagination from CosmosDB below and explain how it works.
The Solution
This article will assume that you’ve followed the instructions on the official Microsoft SQL Api Node.JS example app or at minimum have an existing CosmosDB and an existing Model file that can succesfully connect to the database. If you’ve not done this then check it out at the link below –
Build a Node.js web app using the JavaScript SDK to manage a SQL API account in Azure Cosmos DB
You likely have a model very similar to below that allows you to retrieve some type of result from the database, in my case this looks like the function below –
async getAll() {
const querySpec = "SELECT * FROM root r"
const resources = await this.find(querySpec)
return resources;
}
This simply returns all records from a collection in CosmosDB that I configured at a higher level.
Returning a paginated version of the same is as simple as changing it as follows –
async getAll(continuationToken = undefined) {
const querySpec = "SELECT * FROM root r"
const results = await this.container.items.query(querySpec, {
maxItemCount: 5,
partitionKey: undefined,
continuationToken
}).fetchNext();
return {
items: results.resources,
nextPageToken: results.continuationToken
};
}
This will return 5 records at most and will not limit by any particular partition. It will also return the first page of results.
To return the second page you would use the value retrieved from the nextPageToken value as the continuationToken input. This may look as below in a simplified example –
getAll("+RID:~w1wHAJy6eZcGAAAAAAAAAA==#RT:1#TRC:5#ISV:2#IEO:65567#QCF:4
<eval>/VM46947609:619")