M
M
Maxim Nikitin2015-12-29 15:38:01
JavaScript
Maxim Nikitin, 2015-12-29 15:38:01

Why doesn't findRandom() work in mongoose for node.js?

Circuit description:

var mongoose = require("mongoose");
var random = require('mongoose-random');

var productSchema = new mongoose.Schema(
    {
        Name: String,
        Description: String,
        Price: Number,
        Category:  String
    },
    {
        collection: 'sportsStore'
    }
)
productSchema.plugin(random, {path: 'r'});

var products = mongoose.model('sportsStore', productSchema);
module.exports = products;

Where findRandom() is called
getRandomProducts: function (count) {
        products.findRandom().limit(count).exec(function(error, result) {
            console.log(result);
        })

In the console we get [].
There are documents in the collection, a simple find() works. Where is the problem? Tell me, please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Shikanov, 2015-12-29
@MaxSter

This plugin adds a field to the model, which is then used for sorting, respectively, if you have documents in the collection that were not added through this model (with the plugin connected), you need to add fields to existing documents:

// if you have an existing collection, it must first by synced.
// this will add random data for the `path` key for each doc.
Song.syncRandom(function (err, result) {
  console.log(result.updated);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question