Let's say we want to query a data set and get paginated result sets. In this example we're going to query a set of cities of the world, looking for those based in the USA. Our query is:
{
selector: { country: 'US'},
limit: 50
}
The Node.js to perform this search is as follows:
const Cloudant = require('@cloudant/cloudant')
const cloudant = Cloudant({url: process.env.COUCH_URL})
const db = cloudant.db.use('cities')
db.find({ selector: { country: 'US'}, limit: 50}).then(console.log)
The data returned follows the following form:
{
"docs": [ ... ],
"bookmark": ""
}
The returned documents appear in the docs
array and the bookmark
is our key to the next page of data. To get the next page simply pass the returned "bookmark" in your next query:
const Cloudant = require('@cloudant/cloudant')
const cloudant = Cloudant({url: process.env.COUCH_URL})
const db = cloudant.db.use('cities')
// this is the bookmark taken from the first result set
const bookmark = 'g1AAAAA-eJzLYWBgYMpgSmHgKy5JLCrJTq2MT8lPzkzJBYqzmxgampoYGoGkOWDSyBJZAO7zD4c'
// repeat the query but pass the preceeding bookmark in too
db.find({ selector: { country: 'US'}, limit: 50, bookmark: bookmark}).then(console.log)
The query should be the same as the first one, but with the addition of the bookmark
attribute. The third page of results can be queried by passing the second bookmark into a third request, and so on.