Mongoose随机文件非顺序

时间:2017-02-27 17:47:32

标签: node.js mongodb mongoose

我有一个node.js项目,我需要使用Mongoose从我的mongoDB数据库中获取8个随机文档。

我的架构:

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

在我的路线文件(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});
    });
});

我如何致电'发现'从我的main.js路由文件中在我的模型中运行?

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容获取$sample的唯一项目,但按<!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript"> window.onload = function() { var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); canvas.width = 345; canvas.height = 410; canvas.style.border = "1px solid white"; var left = document.getElementById("left"); left.addEventListener("click", playerLeft); var x = Math.round(canvas.width/2); var y = Math.round(canvas.width/2); var rectWidth = 5, rectHeight = 5; var fps = 30, frames = 1000/fps; var colour = "white"; var trailColour = "blue"; ctx.fillStyle = colour; ctx.fillRect(x,y,rectWidth,rectHeight); function playerLeft() { ctx.fillStyle = trailColour; ctx.fillRect(x,y,rectWidth,rectHeight); x -= 6; ctx.fillStyle = colour;; ctx.fillRect(x,y,rectWidth,rectHeight); } function playerRight() { ctx.fillStyle = trailColour; ctx.fillRect(x,y,rectWidth,rectHeight); x += 6; ctx.fillStyle = colour; ctx.fillRect(x,y,rectWidth,rectHeight); } function playerUp() { ctx.fillStyle = trailColour; ctx.fillRect(x,y,rectWidth,rectHeight); y -= 6; ctx.fillStyle = colour; ctx.fillRect(x,y,rectWidth,rectHeight); } function playerDown() { ctx.fillStyle = trailColour; ctx.fillRect(x,y,rectWidth,rectHeight); y += 6; ctx.fillStyle = colour; ctx.fillRect(x,y,rectWidth,rectHeight); } } </script> </head> <body style="background-color: black"> <canvas id="canvas"></canvas> <div style="text-align: center; padding: 5px"> <button id="left">Left</button> <button id="up">Up</button> <button id="down">Down</button> <button id="right">Right</button> </div> </body> </html>分组以删除随机结果中可能存在的重复项:

_id

对于代码结构,您可以定义static method db.images.aggregate([{ $sample: { size: 100 } }, { $group: { _id: "$_id", document: { $push: "$$ROOT" } } }, { $limit: itemCount }, { $unwind: "$document" }]) ,将您的mongoose对象存储在快速getRandomItems中,并使用app.db从您的路由器调用mongoose对象:

model.js

req.app.db

app.js

'use strict';

exports = module.exports = function(app, mongoose) {

    var schema = new mongoose.Schema({
        title: String,

        width: String,
        height: String,

    });

    schema.statics.getRandomItems = function(itemCount, cb) {

        this.aggregate([{
            $sample: { size: 100 }
        }, {
            $group: {
                _id: "$_id",
                document: { $push: "$$ROOT" }
            }
        }, {
            $limit: itemCount
        }, {
            $unwind: "$document"
        }], cb);
    };

    app.db.model('Images', schema);
};

routes.js

'use strict';

var mongoose = require('mongoose'),
    express = require('express');

var app = express();

app.db = mongoose.createConnection("mongodb://localhost/testDB");

// config data models
require('./models')(app, mongoose);
require('./routes')(app);

app.listen(8080, function() {

});