Mangosta, eliminando una propiedad del modelo

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 y 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?

preguntado el 30 de enero de 12 a las 19:01

1 Respuestas

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

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.

Respondido 17 Feb 12, 04:02

Seems that you can't do that with ObjectId type fields, but nice way of thinking ! :) - panosru

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.