5

I'm working on a mean.js stack application. When I attempt to call a static function of one of my models I'm getting the error 'SomeItem.createNew is not a function'

I am calling this static method from another static method of a different schema, like so.

Does NOT work:

var SomeItem = require('./some-item.js');

aSchema.statics.createNew = function(body, cb) {
    var newA = new this();

    //create child items
    for (i = 0; i < body.someItems.length; i++ {
        SomeItem.createNew(body.someItems[i], function(err, item) {
    }
}

Does work:

aSchema.statics.createNew = function(body, cb) {
    var newA = new this();

    var SomeItem = require('./some-item.js');

    //create child items
    for (i = 0; i < body.someItems.length; i++ {
        SomeItem.createNew(body.someItems[i], function(err, item) {
    }
}

However if I place the require inside of the static function it works fine. Why is this? I would like to only have to declare 'var SomeItem' only once at the top, not in every function I need to use it.

Sean
  • 2,106
  • 2
  • 16
  • 24

1 Answers1

0

The only reason why putting the require inside of a function changes the behavior is that the module that you require uses some resources that are not available at the moment when the requiring module is started but are available at the moment of first usage of that function.

This should not happen but this is probably what is happening here - a race condition. It's impossible to tell you anything more without seeing the code in question but you definitely need to take a closer look at the required module looking for race conditions and time sensitive state.

More error logging can help to narrow down the problem.

rsp
  • 107,747
  • 29
  • 201
  • 177
  • For some reason when I changed the order of the require modules in my app.js file so that aSchema's file was called first then the problem went away. My app.js file called my api files, which called aSchema's file, which called someItem's file. Do you have any more insight to why this fixed my problem? – Sean Mar 22 '17 at 20:10