0

I want create simply ecommerce project in nextjs and mongoose. I have error on early begning during creating models.

I have simply model like this

import mongoose, { Schema } from 'mongoose';

export interface IProduct {
  name: string;
  price: number;
}

const productSchema = new Schema<IProduct>({
  name: {
    type: String,
  },
  price: {
    type: Number,
  },
});

export default mongoose.model<IProduct>('product', productSchema);

After runing project i gettint error OverwriteModelError: Cannot overwrite product model once compiled.

So i changed export to export default mongoose.models.product || mongoose.model<IProduct>('product', productSchema);.

After that everything seems to work but my models lost types sugestion and instead of

const products: Product[] = await Product.find({});

i have

const products: any[] = await Product.find({});

nerrood
  • 27
  • 6
  • 1
    Does this answer your question? [How to properly use Mongoose models in Next.js?](https://stackoverflow.com/questions/65887351/how-to-properly-use-mongoose-models-in-next-js) – Pavel Bely Jul 19 '23 at 20:19
  • It was worked for first time, after page reload i get again error `Unhandled Runtime Error Error: Cannot overwrite `Product` model once compiled.` – nerrood Jul 19 '23 at 20:41
  • You need to cast the model to preferred type `export default (mongoose.models.product as IProduct) || mongoose.model('product', productSchema);` – Pavel Bely Jul 20 '23 at 06:35
  • It's not working because i getting different error - `TS2352: Conversion of type 'Model' to type 'IProduct' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.   Property 'price' is missing in type 'Model' but required in type 'IProduct'.` – nerrood Jul 20 '23 at 06:53

1 Answers1

0

Try with:

export const Product: mongoose.Model<IProduct> = mongoose.models.product || mongoose.model<IProduct>('product', productSchema);
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29