2

I have these mongoose schemas:

var ItemSchema = new Schema({
    "pieces": Number, 
    "item": { type: Schema.Types.ObjectId, ref: 'Items' }
});

var cartSchema= new Schema({
    "items": [ItemSchema]
});

but when I want to push a new item in items, mongoose add an _id field(on the new item) but I don't understand why.

Lorenzo
  • 215
  • 4
  • 10

2 Answers2

1

Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor. The type assigned is an ObjectId to coincide with MongoDB's default behavior. If you don't want an _id added to your schema at all, you may disable it using this option.

You can only use this option on sub-documents. Mongoose can't save a document without knowing its id, so you will get an error if you try to save a document without an _id.

Link: http://mongoosejs.com/docs/guide.html#_id

Abhyudit Jain
  • 3,640
  • 2
  • 24
  • 32
1

if you want to add item without _id field then you should add { _id: false } in ItemSchema.

var ItemSchema = new Schema({
    "pieces": Number, 
    "item": { type: Schema.Types.ObjectId, ref: 'Items' }
}, { _id: false });
Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68