I have a node.js project and I need to get 8 random documents which are not sequential from my mongoDB database using Mongoose.
My Schema:
var mongoose = require('mongoose');
var random = require('mongoose-simple-random');
var schema = new mongoose.Schema({
title: String,
width:String,
height:String,
});
var Images = mongoose.model('Images', schema);
Images.count().exec(function (err, count) {
// Get a random entry
var random = Math.floor(Math.random() * count)
// Again query all users but only fetch one offset by our random #
Images.find({}).limit(8).skip(random).exec(
function (err, result) {
// Tada! random user
console.log(result)
//res.send(results);
})
})
module.exports = {
Images: Images
};
When calling the function in my route file (Main.js):
var Images = require('../models/images.js');
app.get('/homepage', function(req, res){
var rand = Math.floor(Math.random() * 10000);
Images.find({}).limit(8).skip(rand).exec(function(err, docs){
res.render('homepage', {images: docs});
});
});
How would I call the 'find' function in my model from my main.js route file?