For brief context, I’m creating a web app using ReactJS, Node.js + mongoDB. It’s purpose is to hold lists of meals and products, and from them you can easily create shopping lists.
I’m totally inexperienced with Node.js and MongoDB and learning along the way of creating this app, therefore I need your help to solve an issue.
productSchema in mongoose looks like this:
{
uniqueId: {
type: String,
required: true,
default: () => nanoid(),
index: { unique: true },
},
productName: {
type: String,
required: true,
},
}
mealSchema:
{
uniqueId: {
type: String,
required: true,
default: () => nanoid(),
index: { unique: true },
},
mealName: {
type: String,
required: true,
trim: true,
},
products: [
{
uniqueId: {
type: String,
required: true,
default: () => nanoid(),
index: { unique: true },
},
productName: { type: String, ref: productSchema },
productAmount: Number,
},
],
}
as you can see, the products array in mealSchema is pretty much the same as Product[] but having an extra property of productAmount.
The logic in frontend is that when you create a new Meal, you can add as much products as you want (either select from list of Products (which is retrieved from DB) or create new ones). Then the whole Meal is sent to backend, Meal is created in MongoDB collection and after that, BE also iterates through every product, and if it doesn’t exist in the ‘products’ collection, it is also added there.
I’m having an issue that when I’m trying to create a Meal and add a Product which already exists in the ‘products’ collection, backend returns me an error:
{
"error": "Could not create meal",
"message": "E11000 duplicate key error collection: test.meals index: products.uniqueId_1 dup key: { products.uniqueId: "ukmLU8nDtIXaBA7OzZD6R" }"
}
Can somebody please help me solve this?
2
Answers
here's the meal controller:
and products controller:
The E11000 error is generated by the mongod server. The error means that the server is refusing to create the document because it would cause a duplicate key in an index that was explicitly created with the option ‘unique: true’
The error message indicates that the index named ‘products.uniqueId_1’ in the ‘test.meals’ collection has the unique option, and the document being inserted contains
{ products.uniqueId: "ukmLU8nDtIXaBA7OzZD6R" }
, but that value is already present in another document.Did you intend to restrict that collection so that only one document could reference the same "products.uniqueId" value? If that was not your intention, make sure the field is not tagged unique in your schema and drop the index from the mongod server