2

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.

Krushnal Patel
  • 422
  • 2
  • 14

1 Answers1

1

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)

Inder
  • 1,711
  • 1
  • 3
  • 9
  • So for any model I am using, mongoose automatically adds it to mongoose.models right? Can you share some reference docs for this? Thanks!! – Krushnal Patel May 14 '22 at 15:56
  • @KrushnalPatel Yes, the name has to be same though. You used `mongoose.model("user")` so the name of the model compiled will be the same `mongoose.models.user`. You can take a look at [Nextjs Official Examples](https://github.com/vercel/next.js/tree/canary/examples/with-mongodb-mongoose) – Inder May 14 '22 at 15:59