Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1K
Visualizações
Mongoose NextJS OverwriteModelError: Cannot overwrite `Note` model once compiled

I am learning to use Mongoose with NextJS and I keep running into this error. I have looked over similar questions but didn't figure out how to solve this. I have followed a tutorial video for implementing Mongoose step by step but in the video this problem didn't occur. Also, I hate to say it this inaccurately but it only happens "sometimes". Seems like every time I run the server first POST request always goes through, GET requests are also fine but when I try multiple POST requests it occurs. After restarting the server it works again. Here is my code:

import mongoose from "mongoose"

const connection = {}

async function dbConnect() {
    if (connection.isConnected) {
        retrun
    }

    const db = await mongoose.connect(process.env.MONGO_URI, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })

    connection.isConnected = db.connections[0].readyState
    console.log(connection.isConnected)

}

export default dbConnect
const mongoose = require("mongoose")

let NoteSchema = new mongoose.Schema({
    email: {
        type: String,
        required: [true, "Please enter your email"]
    }
})

module.exports = mongoose.model.Note || mongoose.model("Note", NoteSchema);

import dbConnect from "../../utils/dbConnect"
import Note from "../../models/Note"

dbConnect()

export default async (req, res) => {
    const { method } = req

    switch(method) {
        case "GET":
            try {
                const notes = await Note.find({})

                res.status(200).json({ success: true, data: notes })
            } catch (error) {
                res.status(400).json({ success: false })
            }
            break
        case "POST":
            try {
                const note = await Note.create(req.body)

                res.status(201).json({ success: true, data: note })
            } catch (error) {
                res.status(400).json({ success:false })
            }
            break
        default:
            res.status(400).json({ success:false })
            break
    }
}

Thanks for any help.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

you should use mongoose.models.Note instead of mongoose.model.Note

so just try:

module.exports = mongoose.models.Note || mongoose.model("Note", NoteSchema);

This method is used to prevent overwrite model once compiled Mongoose

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda