Reputation: 299
Hi I have 2 collections that don't have reference to each other, I want to merge both of them in one collection, then I do pagination.
However it's not working, I only get result when page is 1 but for any other pages I just get an empty array
const search = async (skip, limit, query) => {
const regex = new RegExp(`^${query}`, 'i')
const cursor = await db.collection('cats').aggregate([
{ $unionWith: {
coll: 'dogs',
pipeline: [{ $project: { 'breeds': false } }]
}
},
{ $match: { $or: [
{ 'dog_name': { $regex: regex } },
{'cat_name': { $regex: regex } }
]}},
{ $limit: limit },
{ $skip: skip }
]).toArray()
return cursor
}
const result1 = search(0, 10, 'Mi') // This works
const result2 = search(10, 10, 'Mi') // This doesn't page(2)
const result2 = search(20, 10, 'Mi') // This doesn't page(3)
Upvotes: 1
Views: 56
Reputation: 46
Try this:
const cursor = await db.collection('cats').aggregate([
{ $unionWith: {
coll: 'dogs',
pipeline: [{ $project: { 'breeds': false } }]
}
},
{ $match: { $or: [
{ 'dog_name': { $regex: regex } },
{'cat_name': { $regex: regex } }
]}},
{ $skip: skip } ,
{ $limit: limit }
]).toArray()
You are limiting before skipping, maybe that's the issue.
Upvotes: 3