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

191
Visualizações
Mongoose/NodeJS shuffle and limit collection in Controller

I have the below code in my Mongoose/NodeJS controller, which is used to shuffle the records in a collection. The shuffle is working as expected.

In the 'Sliders' collection, I only want to display 4 shuffled records in the front end; however, I want to limit the number of records in the controller rather than slice them in the front end, because there are a lot of records in the collection.

At the moment, my code limits them before it shuffles them, hence it always displays the same 4 records. How can I shuffle the collection in the controller, then subsequently limit to 4 records in the controller, so I can then display them in the front end?

function shuffleArray(array) {
   for (let i = array.length - 1; i > 0; i--) {
       const j = Math.floor(Math.random() * (i + 1));
       [array[i], array[j]] = [array[j], array[i]];
   }
}

const sliders = await Slider.find({ "category": "Slider" }).limit(4);
    shuffleArray(sliders);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Try aggregation with $match and $sample https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate

const agg = Slider.aggregate([
      {$match: {"category": "Slider"}},
      {$sample: { size : 4 }}
]);

const sliders = await agg.exec();
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