Mongoose: Using model or schema provided by a module from npm/node_modules

Say I have an application that defines a few models and creates the global Mongoose connection (mongoose.connect(...)). The app also relies on some models defined by a module in the node_modules directory. The problem that I'm running into is that the application and the separate module do not share the same global connection object.

Okay, fine. Rather than having the module export a model it can just export the schema and the main application can register it with the connection. In the app there would be something like:

var SomeSchema = require('somemodule').SomeSchema;
mongoose.model('SomeModel', SomeSchema);

Unfortunately this isn't working either. When the model is registered, Mongoose is checking whether the given schema is an instance of mongoose.Schema (here). When SomeSchema was defined (in the separate module) it creates the schema with new mongoose.Schema({ ... }) where mongoose is required from the module's local dependency tree. When the application registers the schema it uses the mongoose required from the application's dependencies. Since the two copies of mongoose are not the same object the given schema is not an instance of mongoose.Schema and an error is thrown.

Do you have any recommendations here? I was thinking one potential solution would be to have the module create a "plugin" function that accepts the schema and adds all the paths, methods, etc. The main app would create an empty schema and add the plugin. Something like:

var somePlugin = require('somemodule').somePlugin;
var SomeSchema = new mongoose.Schema();
SomeSchema.plugin(somePlugin);
mongoose.model('SomeModel', SomeSchema);

Are there any alternatives?

Thanks a lot.

I got around this problem by hacking the prototype of the schema to use the correct instance of mongoose.Schema so that it will pass the internal Mongoose instanceof check. So for your example, I would add a line like this:

var SomeSchema = require('somemodule').SomeSchema;
SomeSchema.__proto__ = mongoose.Schema.prototype;
mongoose.model('SomeModel', SomeSchema);

It's certainly not kosher but it works for me!