猫鼬,从模型中删除属性

问题描述:

我正在使用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字段。不过,我已经应用的解决方案,以从数据库中删除空数组,但它不工作:

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(); 
}); 

我测试了本地,它似乎做的工作的罚款。

+0

似乎你不能用ObjectId类型的字段来做到这一点,但不错的思维方式! :) – panosru 2012-03-21 22:40:59