0

I use mongoose random plugin.
In my schema definition i call

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

After that I have a custom static method who use the plugin:

GameSchema.statics.someMethod {  
    [...]
    GameSchema.findRandom...  

And I get the error

TypeError: Object #<Schema> has no method 'findRandom'

Is there a way to achieve what I am trying to do or should I implement some kind of repository ?

EDIT:
Ben's answer worked, I needed to use findRandom on the model and not the schema.
Precision for those in my case: you need to declare first your static function

GameSchema.statics.someMethod {  
    [...]
    Game.findRandom...

then register your schema

var Game = mongoose.model('Game', GameSchema);

otherwise you'll get "Model .... has no method 'someMethod'"
Game variable in the static function is recognized event though it is defined only later in the script.
=> bonus question: does anyone know why it works ?

Nihau
  • 474
  • 3
  • 20

1 Answers1

1

You're calling the method on the schema, whereas you need to be calling it on the model.

var Game = mongoose.model('Game', GameSchema);

Game.findRandom()...
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80
  • It does work this way :) Just a precision: I tried that but I was putting var Game =mongoose.model('Game', GameSchema); before my static function def and therefor getting 'unknow method'. I tried again and put it at the end of the file and now it works (which is still a little odd to me as Game var is not defined when I use it in the static method). – Nihau Sep 19 '14 at 10:55