Mongoose: Nested Schema Array is throwing an error that _id = null and _id cannot be duplicated

36 Views Asked by At

I am building an online ordering website where an orderSchema contains a nested array of itemSchema, however, Mongoose is throwing

E11000 duplicate key error collection: restaurant.orders index: items._id_1 dup key: { items._id: null }

I've tried a few different things but nothing seems to work, I keep getting that items._id is null when I'm not even trying to declare an _id for items.

Here are my models.

const orderSchema: Schema = new Schema({
  customer_name: String,
  phone_number: String,
  _id: String,
  orderItems: [
    {
      _id: Number,
      itemPrice: Number,
      items: [{ type: itemSchema, _id: false }],
      quantity: Number,
      type: { type: String },
    },
  ],
  total: Number,
});

export const itemSchema: Schema = new Schema({
  name: String,
  description: String,
  price: Number,
  _id: String,
  cooking_time: String,
  options: [
    {
      name: String,
      price: Number,
      checked: Boolean,
    },
  ],
  flavors: [
    {
      isValid: Boolean,
      checked: Boolean,
      id: String,
      value: String,
    },
  ],
  sizes: [
    {
      isValid: Boolean,
      checked: Boolean,
      id: String,
      value: String,
      price: Number,
      inches: Number,
    },
  ],
});

the itemSchema needs to have an _id because my menu items are being held in a collection separate from my orders. However, orderItems.items does not need an _id, it's just an array. Essentially I can put one document into my orders db but as soon as I try to create a second document it throws the error. I can't wrap my head around why an array would need an _id, and why declaring _id: false doesn't work even though the individual item id's are unique. Also, not sure if this is related or not, but I try to make my _id's of type Stringbut mongoose keeps converting them to Double's. Also, yes, I've looked at other posts about the same topic, but none of those have been helping. I've tried a lot of different things at this point.

0

There are 0 best solutions below