Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose, Removing a Property from Model

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?

like image 492
Mustafa Avatar asked Jan 30 '12 19:01

Mustafa


1 Answers

You can use a pre-save hook to check for those empty fields, and set them to undefined like this:

PostSchema.pre('save', function (next) {
    if(this.pictures.length == 0){
        this.pictures = undefined;
    }
    if(this.cast.length == 0){ 
        this.cast = undefined;
    }

    next();
});

I tested this locally and it seems to do the job fine.

like image 188
mpobrien Avatar answered Nov 08 '22 11:11

mpobrien