lundi 25 septembre 2017

Mongoose get a random element except one

I have a collection of articles in mongodb. I choose an article that i want to render, and I want two other articles chosen randomly. I want to pick two articles in my collection that are not the same, and are not the article I have chosen before. Been on this problem for hours, search for a solution but only found how to pick an element randomly, but not except one...

Here is what I have now :

article.find({}, function(err, articles{   
    var articleChosen = articles.filter(selectArticleUrl, articleUrl)[0];
    article.find({})
    .lean()
    .distinct("_id")
    .exec(function(err, arrayIds){  
      var articleChosenIndex = arrayIds.indexOf(articleChosen._id);
      arrayIds.splice(articleChosenIndex, 1);
      chooseRdmArticle(arrayIds, function(articleRdm1Id){
        var articleRmd1 = articles.filter(selectArticleId, articleRdm1Id)[0];
        var articleRdm1Index = arrayIds.indexOf(articleRdm1Id);
        arrayIds.splice(articleRdm1Index, 1);
        chooseRdmArticle(arrayIds, function(articleRdm2Id){
          var articleRmd2 = articles.filter(selectArticleId, articleRdm2Id)[0];
          // do stuff with articleChosen, articleRmd1 and articleRmd2
        })
      })
    })
  })

where the function which choose rdm article is :

function chooseRdmArticle(articles, callback){
  var min = Math.ceil(0);
  var max = Math.floor(articles.length);
  var rdm = Math.floor(Math.random() * (max - min)) + min;
  callback(articles[rdm])
}

and the function which select the article from its url is :

function selectArticleUrl(element){
  return element.url == this
}

My idea was to work on the array containing all the ObjectId (arrayIds here), to choose two Ids randomly after removing the articleChosen id. But I understood that arrayIds.indexOf(articleRdm1Id); couldn't work because ObjectIds are not strings ... Is there a method to find the index of the Id I want? Or any better idea ?

Thanks a lot !




Aucun commentaire:

Enregistrer un commentaire