I want to paginate the field rating of my product collection. Upon trying this query on mongo shell,
db.products.find({_id: ObjectId('610bd9233fdc66100f703dd4')}, {ratings: {$slice: [1,1]}}).pretty();
I got the expected result. Which is just one item from the rating field.
But I have tried the following queries using mongoose in my application but it keeps returning all the items in the ratings array.
const ratings = await Product.find({_id}).slice("ratings",[1, 1]).select("ratings").populate(populateQuery);
const ratings = await Product.find({_id}, {ratings: {$slice: [1, 1]}}).select("ratings").populate(populateQuery);
I have checked mongoose website to be sure I am doing this right. Mongoose Slice reference. I have also tried using this previously asked question Pagination on array stored in a document field
What am I doing wrong please. I have upgraded my mongoose package to the latest version also
Query.projection replace the projection on the query, so after running
.slice("ratings",[1, 1])
The projection will be {ratings: {$slice:[1,1]}}
Query.select modifies the projection in place, so after running
.select("ratings")
the ratings field of the projection will be set to 1, so the resulting projection is: {ratings: 1}.
remove .select("ratings") from that line and it should work the way you intended.