0

I have this code:

router.get("/index/fill", function(req, res){
  var topicId = req.query.topicId;

  Topics.findById(topicId, function(err, topic){
    if(err){
      console.log(err);
    } else {
      var random = Math.floor(Math.random() * 115)
      Playlist.find({$or: [{title: new RegExp(topic.title, 'i')}]}).sort({date: -1}).limit(1).skip(random).exec(function(err, recentPlaylists){
        if(err){
          console.log(err);
        } else {

        }
      }); 
    }
  });
});

I found out that .skip() is not working, when I use the code without .skip() part it works.
I followed this post to write the code.

When i use .skip() it returns a empty array.

What am I doing wrong with the .skip() and how can I fix this?

Bruno Pigatto
  • 67
  • 2
  • 13

1 Answers1

2

Your .limit() is before .skip. so you always return 1 record and then skip whatever Math.Random returns ... hence no results.

Switch them around so you first skip then limit.

Also mongoDB has its own regex operator $regex:

{ title: { $regex: /pattern/, $options: 'i' }}

For "random" records use $sample:

db.getCollection('<YouColName>').aggregate([
{ $sample: { size: 3 } }
])
Akrion
  • 18,117
  • 1
  • 34
  • 54
  • I switched them and I still have an empty array. – Bruno Pigatto Aug 08 '18 at 19:25
  • Can you put as a skip parameter `1` instead of the random and see if then you get results? Also mongoose has a regex so you can do `{ title: { $regex: //i, $options: 'i'}}` – Akrion Aug 08 '18 at 19:29
  • 1
    Well you should use the build in `$regex` if you could. If this helped you solve the issue, mark this as the answer so others can find it easier etc. Glad it worked. – Akrion Aug 08 '18 at 19:37
  • With `skip(1)` the result is always the same. And what i should write in ? I dont know what this is – Bruno Pigatto Aug 08 '18 at 19:49
  • So basically you have proven that the issue is in your skip parameter which seems to be bigger than the results returned. You math random number is larger than your result set and that is the reason you get no results. The `$regex` is just a suggestion you can read in the doc link I posted how to utilize it. If current regex use works for you ... you do not have to change it :) – Akrion Aug 08 '18 at 19:51
  • I tried `$regex: /^a/, $options: 'i'` and also changed the limit to `5` but it returns the first 5 playlists, and the result is always the same 5 playlists, how can I return 5 random playlists that have one of the words of `topic.title`? – Bruno Pigatto Aug 08 '18 at 20:13
  • I never used patterns so Im really confused, sorry – Bruno Pigatto Aug 08 '18 at 20:13
  • Updated the answer. You can just use $sample and no `skip/limit` check the docs: https://docs.mongodb.com/manual/reference/operator/aggregation/sample/ – Akrion Aug 08 '18 at 20:19
  • It worked now, just had to make some adjustments. Thank You very much – Bruno Pigatto Aug 08 '18 at 21:04