I have 2 collections: User and Topic. This is what each model look like.
- User -
{
_id: ObjectId
...
topics: [ObjectId(topic1Id), ObjectId(topic2Id)]
}
- Topic -
{
_id: ObjectId,
...,
author: ObjectId(authorId)
}
I'm trying to get all topics that belong to one user and paginate those topics. Below is the query I'm using:
const aggregate = await Topic.aggregate([{ $match: { author: user._id } }]);
const result = await Topic.aggregatePaginate(aggregate, {page: 1, limit: 2} };
The result I got back includes all Topic documents, instead of the ones that match the query in $match
. I did some console.log and aggregate
returns the correct docs but for some reason, when it goes through aggregatePaginate
, all docs are returned to me.
I did make sure that the user._id
is an ObjectId so that's not a problem.
Please let me know if you need anymore details and please help, I've been spending hours on this and I can't figure it out :'(
To use mongoose-aggregate-paginate-v2 ensure you have imported the module:
const aggregatePaginate = require("mongoose-aggregate-paginate-v2");
or
import aggregatePaginate from "mongoose-aggregate-paginate-v2";
Then register it as a plugin:
topicSchema.plugin(aggregatePaginate);
Now all you need to do is construct your aggregate without executing it like so, this means no await
keyword or then
blocks:
const aggregate = Topic.aggregate([{ $match: { author: user._id } }]);
The aggregate
then gets passed to your query:
const result = await Topic.aggregatePaginate(aggregate, {page: 1, limit: 2} };