MongoDB Error Cannot Override Model Once Compiled with Next.js
So, I started learning this thing called MongoDB. Long story short, I wanted to create backend and I decided to use MongoDB so my Next.js-UI-part has dynamic data. This is new thing for me.
It went smooth. I could create the GET, POST, and DELETE method. Cool cool, fun fun. But then when I tried to create PUT method, a horrible thing happened. An error!
The error in question was like, haaa! dumb dumb!
MongooseError [OverwriteModelError]: Cannot overwrite `Section` model once compiled.
there were like 10++ lines here
message: 'Cannot overwrite `Section` model once compiled.',
5 mins, 30 mins, an hour passed. The error stayed still.
Based from what I know, please correct me if I was wrong, this error occurs as a result of trying to override the same model. And it's actually easy to fix.
Solution: create a fallback on my model.
import mongoose, { Schema } from "mongoose";
const data = new Schema(
{
title: String,
description: String,
},
{
timestamps: true,
}
);
const AllDatabase = mongoose.models.AllDatabase || mongoose.model("AllDatabase", data);
This falback will first see, if the AllDatabase model is exist, then use it. But if it isn't there, create one.
And that's it.