Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error while reloading nextjs server while using mongoose

I am using NextJS as my framework along with Mongoose. I have seen a few tutorials to implement caching for Mongoose but everytime I make some changes in my code while the NextJS server is running, I get this error:

error - OverwriteModelError: Cannot overwrite `user` model once compiled.

I already know why this error is happening from these links:

These are my schema and mongoose config file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// Mongoose connection file
import mongoose from 'mongoose';
import { config } from 'dotenv';
config();

let { MONGODB_URI, MONGODB_DB } = process.env;
let cached = global.mongoose;

if (!cached)
  cached = global.mongoose = { conn: null, promise: null };

export async function connectToDatabase() {
  if (cached.conn)
    return cached.conn;

  if (!cached.promise) {
    /** @type {import('mongoose').ConnectOptions} */
    const opts = { dbName: MONGODB_DB };

    /** @type {import('mongoose')} */
    cached.promise = mongoose.connect(MONGODB_URI, opts).then(mongoose => {
      return mongoose;
    });
  }
  cached.conn = await cached.promise;

  return cached.conn;
}

// Mongoose schema file
import mongoose from 'mongoose';
import { connectToDatabase } from '../config/mongoose';

let db =  await connectToDatabase();
const userSchema = new mongoose.Schema({
    ...some schema
});

let User = db.model('user', userSchema);
export default User;

What I am not able to figure out is what’s causing it and how to resolve it.

>Solution :

You’re getting this error because everytime you hit the api endpoint, mongoose is re-compiling the model. Change your model file this way.
Now, there is a check if model is already compiled, use that otherwise create the model

Also, call connectDb() in api endpoint.

import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
    ...some schema
});

export default mongoose.models.user || mongoose.model('user', userSchema)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading