How to Fix Mongoose Cannot Overwrite Model Once Compiled Error

January 04, 2020

If you’re using mongoose library with serverless framework, then you might have run to the following issue

Cannot overwrite YOUR_MODEL_NAME model once compiled.

As the error suggest this error occurs as a result of trying to override the same model again.

And you can actually fix it pretty easily.

Just assign the model only if it’s not assigned already

Here’s a quick example of how to do it.

const mongoose = require('mongoose');

const { Schema } = mongoose;
mongoose.Promise = global.Promise;

const customerSchema = new Schema(
        name: {
            type: String,
            required: 'Please supply a name',
            trim: true
        email: {
            type: String,
            unique: true,
            lowercase: true,
            trim: true,
            required: 'Please Supply an email address'

module.exports =
    mongoose.models.Customer || mongoose.model('Customer', customerSchema);

👋 I'm Ashik Nesin • Frontend Engineer @Chargebee 👨‍💻• I write about modern Javascript & building web apps

© 2021 Nesin Technologies LLP