我刚刚打开nodeJS
代码尝试使用mongoose-random从我的mongoose
集合中获取随机文档,但出于任何原因我致电findRandom()
时方法,它会回复500
。
test.js
下面我粘贴我的代码:
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;
阅读其他帖子here作为使用syncRandom()
方法的解决方案,但这对我不起作用。都没有使用random()
有任何帮助吗?谢谢你的建议。
更新
进一步深入研究这个问题,我已经知道我的模型TestSchema
应该包含mongoose-random
方法,因此我只有我的静态方法。
答案 0 :(得分:1)
不要将statics
设置为新对象,只需向其中添加方法:
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);
}
});
});
};
但是,如果您的MongoDB服务器至少为3.2,那么您最好使用内置的$sample
管道运算符而不是插件来选择随机文档。
test.aggregate([{$sample: 10}], callback);