Home > Blockchain >  Mongoose/NodeJS shuffle and limit collection in Controller
Mongoose/NodeJS shuffle and limit collection in Controller

Time:02-14

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);

CodePudding user response:

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();
  • Related