Cannot overwrite model once compiled Mongoose
Another reason you might get this error is if you use the same model in different files but your require
path has a different case.
For example, in my situation I had require('./models/User')
in one file, and then in another file where I needed access to the User model, I had require('./models/user')
.
I guess the lookup for modules & mongoose is treating it as a different file. Once I made sure the case matched in both it was no longer an issue.
The error is occurring because you already have a schema defined, and then you are defining the schema again. Generally what you should do is instantiate the schema once, and then have a global object call it when it needs it.
For example:
user_model.js
var mongoose = require('mongoose');var Schema = mongoose.Schema;var userSchema = new Schema({ name:String, email:String, password:String, phone:Number, _enabled:Boolean});module.exports = mongoose.model('users', userSchema);
check.js
var mongoose = require('mongoose');var User = require('./user_model.js');var db = mongoose.createConnection('localhost', 'event-db');db.on('error', console.error.bind(console, 'connection error:'));var a1= db.once('open',function(){ User.find({},{},function (err, users) { mongoose.connection.close(); console.log("Username supplied"+username); //doSomethingHere })});
insert.js
var mongoose = require('mongoose');var User = require('./user_model.js');mongoose.connect('mongodb://localhost/event-db');var new_user = new User({ name:req.body.name , email: req.body.email , password: req.body.password , phone: req.body.phone , _enabled:false });new_user.save(function(err){ if(err) console.log(err); });
I had this issue while 'watching' tests.When the tests were edited, the watch re-ran the tests, but they failed due to this very reason.
I fixed it by checking if the model exists then use it, else create it.
import mongoose from 'mongoose';import user from './schemas/user';export const User = mongoose.models.User || mongoose.model('User', user);