猫鼬,从模型中删除属性

时间:2012-01-30 19:31:36

标签: node.js mongodb 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字段。但是,我已经应用了一个解决方案来从数据库中删除空数组,但它不起作用:

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!

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

1 个答案:

答案 0 :(得分:9)

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

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

    next();
});

我在本地进行了测试,似乎做得很好。