Mongoose remove empty object from inline documents into array
Notice the following code, which shows a schema with two arrays, one set to type:
[ mongoose.Schema.Types.Mixed ]
and one of them is set to 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 am updating 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 can I prevent this removal of b: {}?
EDIT
It turns out this only happens when there is an embedded document inside the array.
source to share
This approach involves first fetching the document from Mongo and then issuing an update command (triggered by the save call). Take a look at the following code.
var id = "54619b5ef610b70b14a46e79";
Tweak.findById(id, function(err, result) {
if (err) {
console.log(err);
}
console.log(result.withSchema[0].value);
result.withSchema[0].value = data.withSchema[0].value;
result.withoutSchema.value = data.withoutSchema.value;
result.save(function(err) {
if (err) {
console.log(err);
}
console.log('updated');
});
});
After saving the document, run the code snippet with the appropriate "id" value.
source to share
Objects that are evaluated before null
(like your b) are skipped by the mongoose. Since an empty or non-existent object evaluates to a value null
in all MongoDB drivers and even in shell queries, this does not actually affect b
whether it is kept empty or not.
For example, if you are asking whether b exists because it is b
empty, it evaluates to null
, and hence the request will fail for that document, whether b
empty or simply not there.
Since you are already using the parameter minimize
, I am assuming the empty result, since it evaluates to null, just does not show up. When validating with a shell, the key should be there with an empty value.
Bottom line: For all practical purposes, it doesn't matter if b is empty or just doesn't exist.
source to share