I'm building a Next.js application with TypeScript and MongoDB/Mongoose. I started running into an error when using Mongoose models, which was causing them to attempt an overwrite of the Model every time it was used.
Code causing Model Overwrite error:
import mongoose from 'mongoose';
const { Schema } = mongoose;
const categorySchema = new Schema({
name: {type: String, required: true},
color: {type: String, required: true}
})
export default mongoose.model('Category', categorySchema, 'categories')
I found that on many projects using Next.js and Mongoose, including the example project by Next.js, they used the following syntax on the export to fix this problem:
export default mongoose.models.Category || mongoose.model('Category', categorySchema, 'categories')
This feels pretty weird and "bandaid solution"-esque, but it seems to do the trick at first glance; it prevents an overwrite if the model already exists. However, using TypeScript I started running into another problem, which after some time I found was being caused by that very line. Since the export was finnicky, TypeScript couldn't parse the Category model, and threw errors whenever I tried to use most of its properties or methods. I looked deeper into it and found some other people going around this by doing:
import mongoose from 'mongoose';
const { Schema } = mongoose;
const categorySchema = new Schema({
name: {type: String, required: true},
color: {type: String, required: true}
})
interface CategoryFields {
name: string,
color: string
}
type CategoryDocument = mongoose.Document & CategoryFields
export default (mongoose.models.Category as mongoose.Model<CategoryDocument>) || mongoose.model('Category', categorySchema, 'categories')
Again, this seems to do the trick but it's merely tricking TypeScript into believing there's nothing weird going on, when in reality there is.
Is there no real solution to fix the Model Overwrite problem without jumping through hoops and covering errors with other errors?
Thanks in advance!
mongoose.models.Customr || ...
part was meant to avoid re-registering the model on file change. Doesn't the lineconst CustomerModel = ...
cause OverwriteModelErrors? – Balls