How to create and export mongoose models correctly inside Next JS
Post by: Niraj Dhungana
Posted on: Nov 14, 2021
#MongoDB# Next JS# Mongoose
Overwrite Model Error: cannot overwrite
YourModel model once compiled.
This is the error which you will see inside the terminal if you don’t use the correct way to create and export your mongoose model inside your Next JS application.
Let’s see first the reason for this error, Overwrite Model Error: cannot overwrite…
Why is this error?
If you read this error carefully you will understand the problem. This error comes inside the node express app if we use the same name to create mongoose models.
But here inside our next js project we are not using the same name to create multiple mongo models. Still we will get this error and that is because Next JS doesn’t work like an actual node express server.
This is code familiar to us or at least to those who already know how to work with node js and mongoose. What is wrong with this code? Nothing if you are working it inside a bare node server.
Why does this error come inside Next JS?
Inside Next JS whenever you try to call the model inside another file to read or add the records. Next JS will try to create a new model every time using the
But we don't want to create a model every time we only want to create it for the first time when we don't have that model ready. After that we want to use the model which we have already created.
How to fix it?
The fix is simple if you don’t know then mongoose holds all the data about the previously created models. So, if you try to access *mongoose.models.MODEL*. You will get what I mean.
For example if you want to create a model called
Post. Then you can create a schema using the
mongoose.Schema(). And then when you are exporting the model with
mongoose.model. Use this code.
Here we are first checking if there is already a model called
mongoose.models. Use that one or if not then create a new one with
And that little question mark is a condition incase if you don’t know. If you don’t put it there and if your
undefined. Then your code will crash with an error cannot read property Post of undefined.
So, that was the reasons and the solutions also. If you have anything to say you can DM me on @ndpniraj.