Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose is removing empty object out of embedded documents in array

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.

like image 829
ekeren Avatar asked Nov 02 '14 20:11

ekeren


1 Answers

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

like image 187
vivek rao Avatar answered Nov 04 '22 15:11

vivek rao