Mongoose model testing require models Mongoose model testing require models mongoose mongoose

Mongoose model testing require models


The problem is that you cant set mongoose model twice. The easiest way to solve your problem is to take advantage of node.js require function.

Node.js caches all calls to require to prevent your model from initializing twice. But you wrapping your models with functions. Unwrapping 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);

Alternative solution is to make sure that each model initialized only once. For example, you can initialize all you modules before running your tests:

Address = require('../models/Address.js');User = require('../models/User.js');Organization = require('../models/Organization.js');// run your tests using Address, User and Organization

Or you can add try catch statement 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 /models/index.js file to handle everything. First, it calls mongoose.connect to establish connection. Then it requires every model in models directory and creates a dictionary of it. So, when we need some model (e.g. user) we requires it by calling require('/models').user.


Best solution (IMO):

try {  mongoose.model('config')} catch (_) {  mongoose.model('config', schema)}


This question already has an answer, but for a unique way to accomplish this check out https://github.com/fbeshears/register_models. This sample project uses a register_models.js that includes all models from an array of file names. It works really well and you end up with all your models pretty much wherever you need them. Keep in mind node.js's cache will cache objects in your project while it's running.