15

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

Totty.js
  • 15,563
  • 31
  • 103
  • 175

2 Answers2

32

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.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • oh, that's ugly to... But here is what I'm doing: when I'm creating the models I set a method on the model itself. (Job.abc = function(){}) I think this is static. It's there any other way to pass a function to a instance? – Totty.js Jan 11 '13 at 14:02
  • Why aren't you adding that function to the schema's `statics` instead? – JohnnyHK Jan 11 '13 at 14:06
  • I don't have access to that static. But your method works too.. I would like something more shorter sintax, but I can live with it. If you come to mind with something more compact, I'm glad to hear – Totty.js Jan 11 '13 at 14:13
  • 4
    Doesn't `this.constructor === this.model(this.constructor.modelName)`? – numbers1311407 Aug 06 '13 at 17:23
  • Calling Job.someStatic() from dynamic method did not even work for me... this.constructor had the right pointer though! – pronebird Aug 02 '15 at 15:03
  • I have the same problem but the solution mentioned in this answer does not work for Mongoose 4.4.x. Anyone got a clue how to do this in a later Mongoose version? – Martijn Apr 14 '16 at 15:08
  • 1
    @Martijn I just tested this with Mongoose 4.4.12 and it worked fine. Best to post a new question about it if you can't get it working. – JohnnyHK Apr 15 '16 at 00:50
1

Another option to access statics is:

this.schema.statics.someStatic()
tamir
  • 3,207
  • 2
  • 33
  • 51