Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a static method from a instance method in mongoose?

How to access a static method from a instance method in mongoose?

I have a job model named Job. From a instance method job.start I want to call the static method Job.someStatic(). How do I get the reference to the Job, from the "this" in the instance method?

thanks

like image 598
Totty.js Avatar asked Jan 11 '13 11:01

Totty.js


2 Answers

The only way I've found to do that generically (without just calling Job.someStatic()) is:

this.model(this.constructor.modelName).someStatic();

Update thanks to @numbers1311407:

I don't know if it's always been the case, but as of at least Mongoose 3.6.11, you can shorten this to:

this.constructor.someStatic();

Mongoose 4.x Update

This still works in 4.4.12.

like image 107
JohnnyHK Avatar answered Sep 28 '22 13:09

JohnnyHK


Another option to access statics is:

this.schema.statics.someStatic()
like image 41
tamir Avatar answered Sep 28 '22 13:09

tamir