Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
Pagination of array field type on mongoose not working but works on mongo shell

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!