Reputation:
While working on MongoDB.I have a problem with doing Pagination.When I'm trying to include Paginaiton with aggerate.I'm also trying to include facets
in this.
My code: Just for doing search
app.get("/search", async(req, res) => {
try {
const text = req.query.text
let result = await collection.aggregate([
{
'$search': {
'text': {
'query': `${text}`,
'path': 'title'
}
}
}
]).toArray();
res.send(result)
} catch (error) {
console.error(error)
}
})
This works for both search
as well as pagination
.
like this, see, It doesn't require any optional request.query.page
.
http://localhost:4000/search?text=mango
http://localhost:4000/search?text=mango?page=1
Now, I want to include the pagination
with facets search as well...So,
server.get("/search", async(req, res) => {
try {
const key = req.query.key;
const value = req.query.value;
const text = req.query.text;
const page = req.query.page; //Page query create
let result = await collection.aggregate([
{
'$search': {
'text': {
'query': `${text}`,
'path': 'title'
}
}
},
{
'$match': {
[key]: `${value}`
}
}
]).toArray();
res.send(result)
} catch (error) {
console.error(error)
}
})
work for this: without no.of Pages
http://localhost:4000/search?text=Mango&key=Brand&value=rasna
Doesn't work for Pagination:
http://localhost:4000/search?text=Mango&key=Brand&value=rasna&page=2
where I'm wrong here? Do I need to create any additional function
to make this works or Something else?
Upvotes: 1
Views: 1107
Reputation: 36
you can use both $skip and $limit aggregation pipelines to achieve this purpose. imagine that we want to have only 20 items per page. so our code looks like this:
server.get("/search", async(req, res) => {
try {
const key = req.query.key;
const value = req.query.value;
const text = req.query.text;
const page = req.query.page - 1; //We subtract one because we don't want skip first twenty items in first page
let result = await collection.aggregate([
{
'$search': {
'text': {
'query': `${text}`,
'path': 'title'
}
}
},
{
'$match': {
[key]: `${value}`
}
},
{ $skip: page * 20 },
{ $limit: 20 }
]).toArray();
res.send(result)
} catch (error) {
console.error(error)
}
})
Upvotes: 1