Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

81
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.

7 months ago ยท Juan Pablo Isaza
Answer question
Find remote jobs