mongoose,从模型中删除一个属性

我正在使用Node.js和Mongoose来存储一些数据。 更新之后,我有以下结构:

{ 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 } 

我需要删除例如在这个文件上的castpictures领域。 但是,我已经应用了一个解决scheme来从数据库中删除空数组,但它不起作用:

 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! 

当保存到数据库时,是否可以从模型中删除空的数组或不需要的值?

您可以使用预保存钩子来检查这些空字段,并将其设置为undefined如下所示:

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

我在本地testing了这个,好像做得很好。