I am using Node.js and Mongoose to store some data. After update, I have the following structure:
{ created: Mon, 30 Jan 2012 19:25:57 GMT,
_id: 4f21a6028132fba40f0000b7,
features:
{ imdb_id: 'tt0822975',
released: '2007-03-24',
tvdb_id: 103191,
type: 'series',
names: [ 'DinoSapien' ],
pictures: [],
cast: [],
genres: [ 'Action and Adventure', 'Children' ] },
type: 1 }
I need to remove e.g. cast and pictures field on this document. However, I have applied a solution to remove empty arrays from the database but it does not work:
instance = (an instance from calling findOne on my model)
cast = (an array)
if ( cast && cast.length > 0){
instance.features.cast = cast;
} else {
delete instance.features.cast;
}
console.log(cast); // null
console.log(instance), // cast is not removed!
Is it possible to remove the empty arrays or unwanted values from model when saving to the db?
You can use a pre-save hook to check for those empty fields, and set them to
undefinedlike this:I tested this locally and it seems to do the job fine.