0

Can I use mongoose SubDocuments recursively? I have this object:

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

and corresponding schemas:

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 = {};
});

But saving this object saves only city without energy. (During PlayerSchema.pre('save', ...) with command this.city = {}; is created Object from CitySchema with default values, but without taking in note method CitySchema.pre('save', ...) which leads to undefined energy attribute in city.)

I would like to avoid populating and making references through ObjectId.

Is possible to save Player object with just subdocuments?

James07
  • 293
  • 1
  • 5
  • 14

1 Answers1

0

Since you are defining the city to be an empty object here:

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

Other than that it should work fine.

raubas
  • 674
  • 7
  • 6
  • In Player after `this.city = {};` mongoose correctly creates a new City with schema default values. In your latter `console.log` the output would be: `{lastUpdate: '2017-03-08...'}`. The problem there is that this attribute `energy: EnergySchema from CitySchema` is missing: Because method `CitySchema.pre('save', ...);` is not called during `PlayerSchema.pre('save',...);` – James07 Mar 08 '17 at 14:57