Edit - It seems I had two issues here. I have accepted the answer given below but please read the comments because the mocha -w issue was just as significant in the fix.
I've read a few SO questions and answers on this and tried a few of the suggested methods but I'm still not able to resolve this issue so I'm hoping someone can help me:
I have a model:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const slug = require('slugs');
const storySchema = new mongoose.Schema({
name :{
type: String,
trim: true,
required: 'Please enter a store name'
},
slug: String,
storyText: {
type: String,
trim:true
},
keyStageLevel: [String]
});
module.exports = mongoose.model('Story', storySchema);
and a storyController:
const mongoose = require('mongoose');
const Story = mongoose.model('Story');
exports.storyHomePage = (req, res) => {
console.log(req.name);
res.render('story', {
title:"Reading Project = Story Home Page",
created:req.query.created
});
};
and I have mocha running some tests. However when I run the test I get an error
MissingSchemaError: Schema hasn't been registered for model "Store".
Reading this https://stackoverflow.com/a/21915511/1699434 I can modify my storyController to
const mongoose = require('mongoose');
mongoose.model('Story', new mongoose.Schema());
const Story = mongoose.model('Story')
which keeps Mocha happy but then nodemon blows up with an error
OverwriteModelError: Cannot overwrite
Storymodel once compiled.
Looking around this https://stackoverflow.com/a/19051909/1699434 seems like the go to answer for this issue but as far as I can see I'm using that approach (I use const Store = mongoose.model('Store');
instead of const Store = require('../models/Store')
)
So I'm a bit stuck. Any help much appreciated!
Edit to include start.js
const mongoose = require('mongoose');
// import environmental variables from our variables.env file
require('dotenv').config({ path: 'variables.env' });
// Connect to our Database and handle any bad connections
mongoose.connect(process.env.DATABASE);
mongoose.Promise = global.Promise; // Tell Mongoose to use ES6 promises
mongoose.connection.on('error', (err) => {
console.error(`${err.message}`);
});
//import all of the models
require('./models/Story');
// Start app
const app = require('./app');
app.set('port', process.env.PORT || 7777);
const server = app.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});