Lorenzo
Lorenzo

Reputation: 225

Mongoose schema

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.

Upvotes: 2

Views: 197

Answers (2)

Shaishab Roy
Shaishab Roy

Reputation: 16805

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 });

Upvotes: 1

Abhyudit Jain
Abhyudit Jain

Reputation: 3748

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

Upvotes: 1

Related Questions