【问题标题】:Why findRandom() mongoose for node.js method doesn't work?为什么 node.js 方法的 findRandom() mongoose 不起作用?
【发布时间】:2015-02-25 16:17:57
【问题描述】:

架构:

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

var productSchema = new mongoose.Schema(...)
productSchema.plugin(random, {path: 'r'});

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

调用findRandom(),控制台显示“[]”

getRandomProducts: function (count) {
    products.findRandom().limit(count).exec(function(error, result) {
        console.log(result);  // -> []
    })

方法 find() 工作正常。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    也许解决方案就在这里 - 请参阅 npm page mongoose-random 示例上的 cmets。

    // if you have an existing collection, it must first by synced.
    // this will add random data for the `path` key for each doc.
    

    试试

    productSchema.syncRandom(function (err, result) {
       console.log(result.updated);
    });
    

    【讨论】:

      【解决方案2】:

      尝试换行

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

      productSchema.plugin(random());
      

      未经测试,但应该可以工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 2018-05-02
        • 2013-01-22
        • 2018-08-06
        • 2012-01-14
        相关资源
        最近更新 更多