Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

322
Views
How to get random records using mongoose?

I found mongoose-random package to get a JSON array of random records using mongoose.

I want to get three random records with a specific field. I read the documentation, but I still didn't find any solution. The following code doesn't work.

app.get('/get/random/song/:language/:gender', function (req, res) {

    var fields = {lang: req.params.language, gender: req.params.gender};
    var filter = {}
    var options = {skip: 3, limit: 3};
    Song.findRandom(filter, fields, options, function (err, songs) {
        res.json(songs);
    });
    
});
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Nowadays you could use aggregate , like this :

this.aggregate([ { $match: { "condition1" : "to_match" , "condition2" : "to_match" } } , { $sample: { size : 3 } } ]);

Where the $sample size is the number of random rows you'll get

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!