notice the following code, that shows a schema with 2 arrays, one is configured to be from Type:
[
mongoose.Schema.Types.Mixed
]
and one is configured to be from type:
[
{
value: mongoose.Schema.Types.Mixed
}
]
Here is the code:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var schema = new mongoose.Schema({
withSchema: [{
value:mongoose.Schema.Types.Mixed}
],
withoutSchema: [mongoose.Schema.Types.Mixed],
} , {minimize: false});
var Tweak = mongoose.model('tweak', schema );
I update the document using the same data:
var data = {
"withSchema" : [ { "value": { a:"221", b:{} } } ],
"withoutSchema" : [ { "value": { a:"221", b:{} } } ]
}
Tweak.findByIdAndUpdate("545680170960023a185ea77e", data, function(err, doc){
console.log(doc);
//{
// "withSchema" : [ { "value": { a:"221" } } ],
// "withoutSchema" : [ { "value": { a:"221", b:{} } } ]
//}
});
How do I prevent this b:{} removal?
EDIT:
It turns out this happens only when there is an embeddedDocument inside an Array.
Removal of empty objects from arrays - is cause by the minimize option of schema - which defaults to 'true'. Erken answered this in a comment in the down voted answer above - putting it as a separate answer so people can find it.
Can be overridden to 'false' in the schema - then it will save empty objects in arrays
var schema = new Schema({ name: String, inventory: {} }, { minimize: false });
from http://mongoosejs.com/docs/guide.html#minimize
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With