Random document from a collection in Mongoose

后端 未结 6 2169
北恋
北恋 2020-12-02 23:45

I want to create a Schema.statics.random function that gets me a random element from the collection. I know there is an example for the native MongoDB driver, b

6条回答
  •  天命终不由人
    2020-12-03 00:01

    If you are not wanting to add "test like" code into your schema, this uses Mongoose queries.

    Model.count().exec(function(err, count){
    
      var random = Math.floor(Math.random() * count);
    
      Model.findOne().skip(random).exec(
        function (err, result) {
    
          // result is random 
    
      });
    
    });
    

提交回复
热议问题