DevStarlight DevStarlight - 7 days ago 5
Javascript Question

mongoose-random response 500

I've just opened a

nodeJS
code trying to get random documents from my
mongoose
collection using mongoose-random, but for any reason when I call to
findRandom()
method, it responses a
500
.

test.js

Here bellow I paste my code:

var mongoose = require('mongoose');
var random = require('mongoose-random');
var Promise = require('bluebird');

mongoose.Promise = Promise;

var TestSchema = new mongoose.Schema({
_id: {
type: Number,
default: 0
}
});

TestSchema.plugin(random, {path: 'r'});

TestSchema.statics = {
start: function (value) {
var array = [], i = 1;
for (i; i < value; i += 1) {
array.push({ _id: i });
}
return this.create(array);
},
getRandom: function () {
return new Promise(function(resolve, reject) {
TestSchema.findRandom().limit(10).exec(function (err, songs) {
if (err) {
reject(err);
} else {
resolve(songs);
}
});
});
}
};

module.exports = mongoose.model('TestSchema', TestSchema);


routes.js

var router = require('express').Router();
var path = require('path');
var Promise = require('bluebird');
var request = require('request');

var test = require('./models/test.js');

router.get('/fill', function (req, res) {
test.start(40)
.then(function () {
res.status(200).send('You can start your hack :)');
})
.catch(function (error) {
res.status(400).send(error);
});
});

router.get('/vote', function (req, res) {
test.getRandom()
.then(function (data) {
res.status(200).send(data);
})
.catch(function (error) {
res.status(400).send(error);
});
});

module.exports = router;


Reading other post here as a solution purposes to use
syncRandom()
method, but that doesn't work for me. Neither using
random()


Any help? Thanks in advice.

UPDATE

Digging more into the issue, I've realiced my model
TestSchema
, which should contain
mongoose-random
methods is being overrided, so I only have my statics methods.

Answer

Don't set statics to a new object, just add methods to it:

TestSchema.statics.start = function (value) {
    var array = [], i = 1;
    for (i; i < value; i += 1) {
      array.push({ _id: i });
    }
    return this.create(array);
  };

TestSchema.statics.getRandom = function () {
    return new Promise(function(resolve, reject) {
      TestSchema.findRandom().limit(10).exec(function (err, songs) {
        if (err) {
          reject(err);
        } else { 
          resolve(songs);
        }
      });
    });
  };

However, if your MongoDB server is at least 3.2, you're probably better off using the built-in $sample pipeline operator instead of a plugin to select random documents.

test.aggregate([{$sample: 10}], callback);
Comments