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;
CodePudding user response:
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.