1

I am creating some rest API with ActionHero js and Mongoose. I put the Mongoose code in an initalizers and everything works. When I modify some files the project automatically recompiles and it returns the following error: OverwriteModelError:

Cannot overwrite User model once compiled.

How should I edit my code to avoid this error? 'use strict';

var mongoose   = require('mongoose');


exports.mongo = function(api, next) {

    mongoose.connect(api.config.mongo.host);

    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function callback () {
        console.log('Connection opened');
    });

    var Schema = mongoose.Schema,
        Types = mongoose.Schema.Types;

    var userSchema = mongoose.Schema({
        createdAt: { type: Date, default: Date.now(), required: true},
        updatedAt: { type: Date, required: false},
        email: { type: String, required: true },
        name: { type: String, required: true },
        surname: { type: String, required: true },
        password: { type: String, required: true },
        roles: [],
        tokens: [{
            code: String,
            expiryDate: { type: Date, default: Date.now() + 30 }
        }]
    });


    var User = mongoose.model('User', userSchema);

    var postSchema = mongoose.Schema({
        createdAt: { type: Date, default: Date.now(), required: true},
        updatedAt: { type: Date, required: false},
        content: { type: String, required: true },
        votes: { type: [Types.ObjectId], ref: 'User' } ,
        coordinates: { type: [Number], index: { type: '2dsphere' }, required: true },
        creator: { type: Schema.Types.ObjectId, ref: 'User', required: true }
    });


    var Post = mongoose.model('Post', postSchema);

    api.mongo = {
        mongoose: mongoose,
        user: User,
        post: Post
    };

    next();
};
Mino
  • 635
  • 10
  • 28

1 Answers1

1

actionhero will reload any initializers if you are in developmentMode. You should wrap your connection steps within the _start() block, rather than have them run in-line each time. This way, actionhero can re-load the file and not re-run your connection steps.

http://actionherojs.com/docs/core/initializers.html

Evan
  • 3,191
  • 4
  • 29
  • 25