mocha --watch and mongoose models mocha --watch and mongoose models mongoose mongoose

mocha --watch and mongoose models


I had the same issue. My solution was to check whether the model was created/compiled yet, and if not then do so, otherwise just retrieve the model.

using mongoose.modelNames() you can get an array of the names of your models. Then use .indexOf to check if the model you want to get is in the array or not. If it is not, then compile the model, for example: mongoose.model("User", UserSchema), but if it is already defined (as is the case with mocha --watch), simply retrieve the model (don't compile it again), which you can do with for example: mongoose.connection.model("User").

This is a function which returns a function to do this checking logic, which itself returns the model (either by compiling it or just retrieving it).

const mongoose = require("mongoose");//returns a function which returns either a compiled model, or a precompiled model//s is a String for the model name e.g. "User", and model is the mongoose Schemafunction getModel(s, model) {  return function() {    return mongoose.modelNames().indexOf(s) === -1      ? mongoose.model(s, model)      : mongoose.connection.model(s);  };}module.exports = getModel;

This means you have to require your model a bit differently, since you are likely replacing something like this:

module.exports = mongoose.model("User", UserSchema);

which returns the model itself, with this:

module.exports = getModel("User", UserSchema);

which returns a function to return the model, either by compiling it or just retrieving it. This means when you require the 'User' model, you would want to call the function returned by getModel:

const UserModel = require("./models/UserModel")();

I hope this helps.


Here is a simpler code for the function getModel() that George is proposing

function getModel(modelName, modelSchema) {  return mongoose.models[modelName] // Check if the model exists   ? mongoose.model(modelName) // If true, only retrieve it   : mongoose.model(modelName, modelSchema) // If false, define it}

For a larger explanation on how to define and require the model, look here

Hope this helps :)