mercredi 27 octobre 2021

how to find random documents without repetition in Mongoose?

I'm working on a nodejs website in which I have Sentences database, and each time I need to randomly display a sentence that is different from the sentences already displayed till all sentences from the database are displayed.

here's some of the code I wrote:

app.get('/sentencePage', (request, response) => {
  var randID =
    request.app.locals.sentences_count[
      Math.floor(Math.random() * request.app.locals.sentences_count.length)
    ];
  Sentence.findOne({})
    .skip(randID)
    .exec(function (err, sentence_obj) {
      var index = request.app.locals.sentences_count.indexOf(randID);
      if (index > -1) {
        request.app.locals.sentences_count.splice(index, 1);
        userObj = UserDetail.findById(
          request.app.locals.user_id,
          function (err, user) {
            if (user.displayed < 20) {
              // update to db
              UserDetail.updateOne(
                { _id: user._id },
                { $inc: { displayed: 1 } },
                function (err, res) {}
              );
              request.app.locals.sentence = sentence_obj;
              response.render('sentencePage', { data: sentence_obj });
            } else {
              response.redirect('/end');
            }
          }
        );
      } else {
        response.redirect('/end');
      }
    });
});

The problem with this code is that sometimes the Sentence.findOne().skip(randID) returns null and then no sentence can be displayed.

I will truely grateful if anyone could has a clue what is the problem.

note that:

sentences_count: array that has the number from 1 to the number of sentences in the database

UserDetail : database that holds information about users

user.displayed: number of sentences already displayed to that specific user.

Thanks




Aucun commentaire:

Enregistrer un commentaire