In my Food
schema, I have different fields based on the other field called yummy
. For example:
yummy
equals pancake
, my fields are dough
and jam
yummy
equals pizza
, my fields are dough
, meat
and cheese
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?
When you are saving the document, mongoose look at the schema of the related collection.
It takes all fields you are giving to it and set the values up. It also create default values for the fields you did provide nothing for.
That's the behavior of mongoose.
In your case what can we do?
We gonna create two schema related to the same collection. One with the field cheese and one without. So when you gonna save a new document with the schema without cheese
, it's not gonna get created.
In practice, the collection will hold two different document type.
Here is a link about using multiple schema related to a single collection