3

Suppose we have a Mongoose object Foo.js.

var mongoose = require('mongoose');

var Bar = require('/path/to/bar');

var Foo = mongoose.Schema({});

Foo.statics.hello = function() {
  console.log('hello from foo');
};

Foo.statics.useBar = function() {
  Bar.hello();
};

module.exports = mongoose.model('Foo', Foo);

As well as a regular javascript object Bar.js.

var Foo = require('/path/to/foo');

var Bar = function() {};

Bar.hello = function() {
  console.log('hello from bar');
};

Bar.useFoo = function() {
  Foo.hello();
};


module.exports = Bar;

If we wanted to call methods in Bar from Foo, everything would be fine. Yet, if we wanted to call methods in Foo from Bar, we would receive an error.

app.use('/test', function(req, res, next) {

  var Foo = require('/path/to/foo');
  var Bar = require('/path/to/bar');

  Foo.hello();
  Bar.hello();

  Foo.useBar();
  Bar.useFoo();

});

The above yields:

hello from foo
hello from bar
hello from bar
TypeError: Foo.hello is not a function

Why does this happen?

Additionally, how do I create an object Bar that can call methods from Foo, but at the same time is not meant to be - and cannot be - persisted into mongodb?

Zsw
  • 3,920
  • 4
  • 29
  • 43

1 Answers1

2

The problem you are experiencing is circular/cyclic dependencies in node.js. It gives you an empty object.

If you change Bar.js like this:

var Bar = function() {};
module.exports = Bar;

var Foo = require('/path/to/foo');

Bar.hello = function() {
  console.log('hello from bar');
};

Bar.useFoo = function() {
  Foo.hello();
};

and then swap the order in app.use to

var Bar = require('/path/to/bar');
var Foo = require('/path/to/foo');

it works for me.

Look at this answer for more information: How to deal with cyclic dependencies in Node.js

Community
  • 1
  • 1
bolav
  • 6,938
  • 2
  • 18
  • 42