最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get random records using mongoose? - Stack Overflow

programmeradmin1浏览0评论

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);
    });
    
});

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);
    });
    
});
Share Improve this question edited Apr 3, 2021 at 15:36 Engin asked Jan 20, 2017 at 16:58 EnginEngin 8258 silver badges22 bronze badges 2
  • 1 Possible duplicate of Random record from MongoDB – Sede Commented Jan 20, 2017 at 17:51
  • possible dupicate of stackoverflow./questions/14644545/… – martinho Commented Jul 31, 2019 at 10:39
Add a ment  | 

1 Answer 1

Reset to default 6

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

发布评论

评论列表(0)

  1. 暂无评论