The problem is that you cannot install the mongoose model twice. The easiest way to solve your problem is to use the node.js require function.
Node.js caches all calls to require so that your model does not initialize twice. But you wrap your models with functions. Deploying them will solve your problem:
var mongoose = require('mongoose'); var config = require('./config'); var organizationSchema = new mongoose.Schema({ name : { type : String }, addresses : { type : [mongoose.model('Address')] } }); module.exports = mongoose.model('Organization', organizationSchema);
An alternative solution is to make sure that each model is initialized only once. For example, you can initialize all modules before running tests:
Address = require('../models/Address.js'); User = require('../models/User.js'); Organization = require('../models/Organization.js');
Or you can add a try catch to your models to handle this special case:
module.exports = function (mongoose, config) { var organizationSchema = new mongoose.Schema({ name : { type : String }, addresses : { type : [mongoose.model('Address')] } }); try { mongoose.model('Organization', organizationSchema); } catch (error) {} return mongoose.model('Organization'); };
Update: In our project, we have a /models/index.js file to handle everything. First, it calls mongoose.connect to establish a connection. Then it requires each model in the models directory and creates a dictionary. So, when we need some kind of model (for example, user ), we require it by calling require('/models').user .
source share