【问题标题】:Mongoose subdocuments possible depthMongoose 子文档可能的深度
【发布时间】:2017-07-28 04:50:54
【问题描述】:

我可以递归使用mongoose SubDocuments 吗? 我有这个对象:

var Player = {
  city: {
    energy: {
      solar: 20,
      fusion: 0
    }
  }
};

和相应的模式:

var PlayerSchema = new Schema({
  city: CitySchema
});
PlayerSchema.pre('save', function(next){
  this.city = {};
});

var EnergySchema = new mongoose.Schema({
  solar: {type: Number, default: 0},
  fusion: {type: Number, default: 0}
});

var CitySchema = new mongoose.Schema({
    last_update: { type: Date, default: Date.now },
    energy: EnergySchema
});

CitySchema.pre('save', function (next) {
  this.energy = {};
});

但是拯救这个物体只能拯救没有能源的城市。 (在PlayerSchema.pre('save', ...) 期间,使用命令this.city = {}; 从CitySchema 中使用默认值创建对象,但没有注意方法CitySchema.pre('save', ...) 这会导致城市中未定义的能量属性。)

我想避免通过 ObjectId 填充和进行引用。

是否可以仅使用子文档保存 Player 对象?

【问题讨论】:

    标签: mongoose odm


    【解决方案1】:

    由于您在这里将城市定义为一个空对象:

    PlayerSchema.pre('save', function(next){
       console.log(this.city); //Should be { energy: { solar, fusion }}
       this.city = {};
       console.log(this.city); //Now {}
    });
    

    除此之外它应该可以正常工作。

    【讨论】:

    • this.city = {}; mongoose 之后的播放器中正确创建了一个具有架构默认值的新城市。在您的后者console.log 中,输出将是:{lastUpdate: '2017-03-08...'}。问题在于缺少此属性energy: EnergySchema from CitySchema:因为在PlayerSchema.pre('save',...);期间未调用方法CitySchema.pre('save', ...);
    猜你喜欢
    • 2018-04-05
    • 1970-01-01
    • 2021-03-29
    • 2012-04-14
    • 2020-03-28
    • 2021-04-29
    • 2018-12-13
    • 2020-07-16
    • 2017-08-13
    相关资源
    最近更新 更多