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


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source