Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
Model identified during hot reload and only fails after server restart

I am connecting to mongodb via mongoose and then creating a model as follows.

// coming from /database/schema
import mongoose from "mongoose";

const kittySchema = new mongoose.Schema({
    name: String
})

const Kitten = mongoose.model("Kitten", kittySchema)

export default Kitten;

This works first time where I am able to insert into the db.

If I try to insert a second time, end up with following error.

OverwriteModelError: Cannot overwrite Kitten model once compiled.

This is cos I am trying to reinsert a model which already exists. So to fix this error, I added a check as follows.

const Kitten = mongoose.model('Kitten') || mongoose.model("Kitten", kittySchema)

This whole time I started the server once locally and been fixing the error while it hot reloads.

Everything works now. Can insert multiple times. But now if I stop the server and restart, I end up with following error.

MissingSchemaError: Schema hasn't been registered for model "Kitten". Use mongoose.model(name, schema)

THIS is the issue. It doesn't like the fix: mongoose.model('Kitten') ||

Why was it ok when I added in while server was on. But facing this error now after I stopped and started server?

P.S: Don't believe the following are relevant. This is how I am connecting and inserting.
Adding them in case needed.

// coming from /database/connection
import mongoose from "mongoose";

const connection = async () => {
    await mongoose.connect(process.env.DB_CONNECTION_STRING)
    console.log('Database connected')
}

export default connection;

import connection from "../database/connection";
import Kitten from "../database/schema";

const saveKittens = (req, res) => {
    connection()
        .catch(error => console.log(`saveKittens error ${error}`))

    const create = new Kitten({ name: 'test123' })
    create.save().then(() => {
        res.status(200).json(create)
    })
}

export default saveKittens;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try to change your model declaration to:

const Kitten = mongoose.models?.Kitten || mongoose.model("Kitten", kittySchema)

It will return the already defined model if present or declare a new one otherwise.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!