Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

439
Views
Cannot solve the 'Model cannot be overwritten once complied' error on mongoose

Problem: So I'm trying to integrate MongoDB into my nextJs project. Here's a library file which connects to the database.

import shopSchema from './Schemas/shopSchema';
let shopModelCached;
async function getShopModel(connectionUrl) {
  if (!shopModelCached) {
    try {
      await mongoose.connect(process.env.MONGO_DB_CONNECTION_STRING);
      const Shop = mongoose.model("shop", shopSchema);
      shopModelCached = Shop;
    } catch (err) {
      throw err;
    }
  }
  return shopModelCached;
}

export default getShopModel;

When I call the function to get the shop model on my getServerSidedProps on my page, which does literally nothing but call the above function to get the Shop model, and then performs simple query to populate the props.

export async function getServerSideProps(context) {
  try {
    const Shop = await getShopModel(
      process.env.MONGO_DB_CONNECTION_STRING
    );
    const shop = await Shop.findOne({
      shopcode: context.params.shopname,
    }).exec();
    return {
      props: {
        shop,
      },
    };
  } catch (err) {
    throw err;
  }
}

This hits me with an error when I recompile modules. It says, 'OverwriteModelError: Cannot overwrite 'shop' model once compiled.'. My approach to handling this was to cache the model so it wouldn't be overwritten, but to no vain.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!