In my Food
schema, I have different fields based on the other field called yummy
. For example:
- if
yummy
equalspancake
, my fields aredough
andjam
- if
yummy
equalspizza
, my fields aredough
,meat
andcheese
etc. It works as expected upon saving docs - I just pass the fields I want to be saved per the document, as none of them are required except yummy
.
So if I save:
{
yummy: 'pizza'
dough: 'thin'
meat : 'peperroni',
cheese: [ObjectId("59a65a4f2170d90b0436ed4b")] // refs to the cheeses collection.
}
My document looks like expected.
The problem is with field of type: Array
. When I save:
{
yummy: 'pancake',
dough: 'thick',
jam: 'blueberry'
}
My document is saved with an additional cheese: []
field. In my schema, cheese is defined as follows:
Mongoose.model('Food', {
...
cheese: {
type: [{ type: Mongoose.Schema.ObjectId, ref: 'Cheese' }],
required: false
},
...
});
I checked if mongo needs the doc to have an array field predefined as empty in case of $push
used in update - it does not. So, the question is: how do I avoid adding an empty array field to my document upon saving?