Anathema.Imbued Anathema.Imbued - 5 months ago 29
Node.js Question

Cannot overwrite model once compiled Mongoose

Not Sure what I'm doing wrong, here is my check.js

var db = mongoose.createConnection('localhost', 'event-db');
db.on('error', console.error.bind(console, 'connection error:'));
var a1= db.once('open',function(){
var user = mongoose.model('users',
{name:String,email:String,password:String,phone:Number,_enabled:Boolean});
user.find({},{},function (err, users) {
mongoose.connection.close();
console.log("Username supplied"+username);
//doSomethingHere })});


and here is my insert.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/event-db')
var user = mongoose.model('users',
{name:String,email:String,password: String,phone:Number,_enabled:Boolean});
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); });}


Whenever I'm trying to run check.js, I'm getting this error

Cannot overwrite 'users' model once compiled.

I understand that this error comes due to mismatching of Schema, but I cannot see where this is happening ? I'm pretty new to mongoose and nodeJS.

Here is what I'm getting from the client interface of my MongoDB:

MongoDB shell version: 2.4.6 connecting to: test
> use event-db
switched to db event-db
> db.users.find()
{ "_id" : ObjectId("52457d8718f83293205aaa95"),
"name" : "MyName",
"email" : "myemail@me.com",
"password" : "myPassword",
"phone" : 900001123,
"_enable" : true
}
>

Answer

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); 
});