Mongoose Duplicate key error on actions.
Unanswered
Tan posted this in #help-forum
TanOP
I am getting duplicate key error on mongoose. I deleted
My product schema :
Previously I had an id field by mistake and i deleted it but still :
Here is my server action :
.next folder form root and updated my mongoose schema but still I am getting this error : MongoServerError: E11000 duplicate key error collection: restaurant.products index: id_1 dup key: { id: null }My product schema :
Previously I had an id field by mistake and i deleted it but still :
import { Schema, model, models } from "mongoose";
const productSchema = new Schema({
title: {
type: String,
required: true,
},
category: {
type: String,
required: true,
},
images: {
type: [String],
required: true,
},
price: {
type: Number,
required: true,
},
rating: {
type: Number,
default: () => Math.floor(Math.random() * 4) + 2, // Generates random number between 2 and 5
required: true,
},
description: {
type: String,
required: true,
},
});
const Product = models.Product || model("Product", productSchema);
export default Product;Here is my server action :
"use server";
import { connectdb } from "@/config/db";
import Product from "../model/Product";
import { revalidatePath } from "next/cache";
export const addProduct = async (product: any) => {
try {
await connectdb();
const { title, description, price, category, images } = product;
const newProduct = new Product({
title,
description,
price,
category,
images,
});
const saved = await newProduct.save();
console.log("SAVED PRODUCT:", saved);
revalidatePath("/admin/products");
revalidatePath("/menu");
return { success: true, message: "Added product successfully !!" };
} catch (err) {
console.log(err);
return { success: false, message: "Internal server error" };
}
};1 Reply
Toyger
you need to check what indexes you have in your mongo cli
https://www.mongodb.com/docs/manual/reference/method/db.collection.getIndexes/
you should have only _id index unique
https://www.mongodb.com/docs/manual/reference/method/db.collection.getIndexes/
you should have only _id index unique