MongoDb: Implementing infinite scroll while shuffling the data at each response

Viewed 184

I have successfully implemented an infinite scroll that displays a list of profiles in the order in which they are saved in the database.
For example, suppose I have this list of profiles:

const profiles = [
  {
    _id: 1,
    name: profile_name_1,
  },
  {
    _id: 2,
    name: profile_name_2,
  },
  {
    _id: 3,
    name: profile_name_3,
  },
  {
    _id: 4,
    name: profile_name_4,
  },
  {
    _id: 5,
    name: profile_name_5,
  },
  {
    _id: 6,
    name: profile_name_6,
  },
  {
    _id: 7,
    name: profile_name_7,
  },
  {
    _id: 8,
    name: profile_name_8,
  },
  {
    _id: 9,
    name: profile_name_9,
  },
  {
    _id: 10,
    name: profile_name_10,
  },
];

I have been able to implement an infinite scroll displaying them in that ORDER with this code:

// @route  GET api/profile/getXNumberOfProfiles
// @desc   Get a certain number of profiles
// @access Public
router.get("/getXNumberOfProfiles", (req, res) => {
  const resultsPerPage = parseInt(req.query.resultsPerPage);
  const page = req.query.page;
  Profile.find()
    .limit(resultsPerPage)
    .skip(resultsPerPage * page)
    .then((profiles) => {
      res.status(200).json({ profiles: profiles});
    })
    .catch((err) => {
      res.status(404).json({ profile: "Error retrieving profiles" });
    });
});

X means that I get to choose how many profiles should be displayed with every scroll. It is determined through the parameter req.query.resultsPerPage.

And with each new scroll, page is incremented by 1.

The problem with this approach is that it will always display the profiles in the order in which they are saved in the database.
WHAT I AM TRYING TO DO IS:
Displaying the profiles in a shuffled manner.
The main problem with this is that if I decide for example to display two random profiles with each scroll, what would guarantee that after all profiles are displayed there will be no duplicates?
In other words, if I load the first two profiles at first, what would guarantee that they would no be loaded again down the road?

The fact that in the previous implementation, the profiles are returned in an orderly manner, means that there will be no duplicates;

0 Answers
Related