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:

// 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)

Leave a Reply