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

190
Views
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 answers
Answer question

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 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!