Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

234
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda