Node.js Mongoose,从模型中删除属性

Node.js Mongoose,从模型中删除属性,node.js,mongodb,mongoose,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: [ 'DinoSap

我正在使用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 }
我需要删除此文档上的例如
cast
pictures
字段。但是,我已经应用了一个解决方案来从数据库中删除空数组,但它不起作用:

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时,是否可以从模型中删除空数组或不需要的值?

您可以使用预保存挂钩检查这些空字段,并将它们设置为未定义的
,如下所示:

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

    next();
});

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

似乎不能用ObjectId类型字段来做这件事,但思路不错!:)