Mongoose creating empty arrays?
Mongoose does do this on purpose, though I'm not sure why. If you set the properties that you don't want stored as undefined
, they will be excluded from the document.
set field as empty for mongo object using mongoose
According to this answer it is done by default in order to enable Model to perform standard operations on arrays which is possible when the array is empty but not when it is null
or undefined
.
However it is possible to completely remove a property with an empty array. According to the latest updates on this thread the following modification to the schema would work:
var questionSchema = new Schema({
items: { type: Array, default: void 0 } // <-- override the array default to be undefined
});
You can set the default to undefined
. From the Mongoose docs:
var ToyBoxSchema = new Schema({
toys: {
type: [ToySchema],
default: undefined
}
});