Search code examples
mongodbmongoosenext.js

Cannot overwrite mongoose model once compiled with Nextjs


Before you close this question, I have read several forums that have the same question as I have but my issue is way different. Even when Im not trying to do anything, even save a model, it still gives me an error of:

cannot overwrite "mongoose" model once compiled

I have a feeling there is something wrong with my schemas because when it was still simpler, it worked fine but as I tried to make it more complex it started to give me that error. Here is my mongoose code:

import mongoose from 'mongoose'

const flashcardItemSchema = new mongoose.Schema({
    term: {
        type:String,
        required: true,
        min:1
    },
    description: {
        type:String,
        required:true,
        min:1
    }
});
const FlashcardItem = mongoose.model("flashcardItem", flashcardItemSchema);

const flashcardSetSchema = new mongoose.Schema({
    title: {
        type: String,
        min: 1,
    },
    flashcards:[flashcardItemSchema],
})

const FlashcardSet = mongoose.model('flashcardSet', flashcardSetSchema )

export {FlashcardItem, FlashcardSet}

I connect to my database when the server runs, so it doesn't disconnect from time to time.

UPDATE

I realized that I'm using nextjs builtin api, meaning the api directory is inside the page directory. I only get the error once the pages get recompiled.


Solution

  • So it turns out that the error came from nextjs trying to remake the model every render. There is an answer here: Mongoose/NextJS - Model is not defined / Cannot overwrite model once compiled but I thought the code was too long and all that fixed mine was just a single line. When trying to save a model in nextjs, it should be written like this:

    const modelName = mongoose.models.modelName || mongoose.model('modelName', flashcardSetSchema )