windows 10 pro office 2019 pro office 365 pro windows 10 home windows 10 enterprise office 2019 home and business office 2016 pro windows 10 education visio 2019 microsoft project 2019 microsoft project 2016 visio professional 2016 windows server 2012 windows server 2016 windows server 2019 Betriebssysteme office software windows server https://softhier.com/ instagram takipçi instagram beğeni instagram görüntüleme instagram otomatik beğeni facebook beğeni facebook sayfa beğenisi facebook takipçi twitter takipçi twitter beğeni twitter retweet youtube izlenme youtube abone instagram

“Cannot overwrite model once compiled” Next.js and Mongoose Schemas

Asked By: Anonymous

First time using Next.js, I’m trying to implement a Node.js server with MongoDB database, schema models and routes.

I’m not sure what I’m doing wrong, since I tried a lot of combinations, as you can see in the comments in my code. I need to use the models but I’m getting the following error:

"OverwriteModelError: Cannot overwrite termscon model once compiled."

server/models/TermsCon.js:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const TermsConSchema = new Schema({
    _id: {
        type: String,
        required: true,
        default: "1"
    },
    text: {
        type: String,
        required: true,
        default: "Lorem Ipsum"
    }
});

// const TermsCon = mongoose.model.termscon || mongoose.model('termscon', TermsConSchema);    
// module.exports = TermsCon;

// module.exports = mongoose.model('termscon', TermsConSchema);
// export default mongoose.model.TermsCon || mongoose.model('termscon', TermsConSchema)
module.exports = TermsCon = mongoose.model('termscon', TermsConSchema);

server/routes/api/termscons.js:

const express = require('express')
const mongoose = require('mongoose');
const router = express.Router()

const TermsCon = require('../../models/TermsCon')
// const TermsCon = mongoose.model('termscon')

router.get('/', (req, res) => {
    TermsCon.find()
    .then(tc => {
        res.json(tc)
    })
});

module.exports = router;

server/index.js:

const express = require('express')
const next = require('next')
const mongoose = require('mongoose')

const port = process.env.PORT || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
    
    mongoose
    .connect(process.env.MONGODB_URI,
        {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useCreateIndex: true
        }
    )
    .then(() => console.log('MongoDB Connected...'))
    .catch(err => console.log(err));    

    const server = express()

    server.use("/api/termscons", require("./routes/api/termscons"))

    server.get('*', (req, res) => {
        return handle(req, res)
    })

    server.listen(port, (err) => {
        if (err) throw err
        console.log(`Server started on port ${port}`)
    })
})

pages/index.js:

import axios from 'axios'
import { useState, useEffect } from 'react'

export default function Home() {     

    const [ tc, setTc ] = useState()
    
      useEffect(() => {
        axios.get('/api/termscons')
          .then(res => {
            setTc(res.data)
          })
          .catch(err =>console.log("ERR: ", err))    
      }, [])
      
      return (
            <div>
              {tc ?
                <p>{tc}</p>
              : null}
            </div>
      )
    }

Is it something wrong with the way I’m exporting my schema? With the way I’m connecting to my MongoDB? The routes? Pages?

Any idea will be much appreciated! Thanks!


Solution

Answered By: Anonymous

So I changed the structure:

  1. I gave up creating a custom server since it didn’t helped me at all in my Next.js app.
    So I don’t have any server/index.js anymore or server/routes/api. Actually, there is no "server" folder at all. I simply created a mongodb connection separatelly to help me connect to my database, wich I call at each server api call, like so:

utils/dbConnect.js:

import mongoose from 'mongoose'

async function dbConnect() {
  await mongoose.connect(process.env.MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
  })
}

export default dbConnect
  1. Since I don’t have a custom server anymore, I don’t have server/routes/api either. So for the api routes I use the default next.js api folder:

pages/api/termscons.js:

import dbConnect from '../../../utils/dbConnect'
import TermsCon from '../../../models/TermsCon'

export default async function handler(req, res) {
  await dbConnect()

  switch (req.method) {
    case 'GET':
      try {
        const tc = await TermsCon.find()
        res.status(200).json(tc)
      } catch (error) {
        res.status(400).json({ itemnotfound: "No item found" })
      }
      break
    default:
      res.status(400).json({ itemnotfound: "No item found" })
      break
  }
}
  1. To conclude, I have a folder with all my models in my app main folder:

models/TermsCon.js:

import mongoose from 'mongoose'

const TermsConSchema = new mongoose.Schema({
    _id: {
        type: String,
        required: true,
        default: "1"
    },
    text: {
        type: String,
        required: true,
        default: "Lorem Ipsum"
    }
});

export default mongoose.models.TermsCon || mongoose.model('termscon', TermsConSchema);

techinplanet staff

instagram volgers kopen volgers kopen buy windows 10 pro buy windows 11 pro


Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno
Alanya escort Manavgat escort Fethiye escort Kemer escort Didim escort Çanakkale escort Aydın escort Muğla escort Tekirdağ escort Manisa escort Balıkesir escort Trabzon escort Elazığ escort Ordu escort Kütahya escort Isparta escort Rize escort Kahramanmaraş escort Yalova escort Giresun escort Yozgat escort Tokat escort Şanlıurfa escort Sivas escort Batman escort Erzurum escort Sinop escort Kırşehir escort Karaman escort Kırıkkale escort Bolu escort Amasya escort Niğde escort Uşak escort Edirne escort Çorum escort Osmaniye escort Zonguldak escort Van escort Erzincan escort Söke escort Bodrum escort Çerkezköy escort Akhisar escort Bandırma escort Ayvacık escort Akçaabat escort Karakoçan escort Altınordu escort Tavşanlı escort Eğirdir escort Ardeşen escort Afşin escort Altınova escort Bulancak escort Sorgun escort Erbaa escort Viranşehir escort Zara escort Kozluk escort Aziziye escort Ayancık escort Kaman escort Ermenek escort Keskin escort Gerede escort Göynücek escort Bor escort Banaz escort Havsa escort Osmancık escort Bahçe escort Alaplı escort Başkale escort Kemah escort Nazilli escort Fethiye escort Çorlu escort Alaşehir escort Altıeylül escort Biga escort Araklı escort Kovancılar escort Fatsa escort Simav escort Yalvaç escort Çayeli escort Dulkadiroğlu escort Çiftlikköy escort Espiye escort Sarıkaya escort Niksar escort Suruç escort Yıldızeli escort Sason escort Horasan escort Boyabat escort Mucur escort Sarıveliler escort Yahşihan escort Göynük escort Gümüşhacıköy escort Çamardı escort Eşme escort İpsala escort Sungurlu escort Hasanbeyli escort Çaycuma escort İpekyolu escort Refahiye escort Kuşadası escort Marmaris escort Süleymanpaşa escort Turgutlu escort Susurluk escort Gelibolu escort Of escort Ünye escort Domaniç escort Fındıklı escort Elbistan escort Çınarcık escort Tirebolu escort Akdağmadeni escort Turhal escort Eyyübiye escort Suşehri escort Yakutiye escort Gerze escort Mengen escort Merzifon escort Ulukışla escort Sivaslı escort Keşan escort Kadirli escort Ereğli escort Özalp escort Tercan escort Efeler escort Didim escort Çine escort Dalaman escort Menteşe escort Milas escort Ortaca escort Seydikemer escort Ergene escort Kapaklı escort Malkara escort Salihli escort Şehzadeler escort Soma escort Yunusemre escort Ayvalık escort Bigadiç escort Burhaniye escort Gönen escort Karesi escort Çan escort Yenice escort Ortahisar escort Yomra escort Perşembe escort Pazar escort Onikişubat escort Pazarcık escort Türkoğlu escort Eynesil escort Görele escort Piraziz escort Yağlıdere escort Çayıralan escort Boğazlıyan escort Zile escort Siverek escort Karaköprü escort Haliliye escort Akçakale escort Şarkışla escort Gemerek escort Oltu escort Palandöken escort Mudurnu escort Suluova escort Taşova escort Toprakkale escort Kilimli escort Tuşba escort Üzümlü escort