2

This is almost certainly covered elsewhere, but:

If I have a single schema with an embedded sub-document, like so:

var ChildSchema = new Schema ({
name : {
        type: String, 
        trim: true
},
user :{
    type: String, 
    trim: true
}
})

var ParentSchema = new Schema ({
name : {
     type: String,
     trim: true
},
child : [ChildSchema]
})

How would I save the name of the ParentSchema to ParentSchema.name and to ChildSchema.name in the same .save() action? The following does not work at all.

ChildSchema.pre('save', function(next){
this.name = ParentSchema.name;
next();
});
pretentiousgit
  • 165
  • 2
  • 9

1 Answers1

1

You can do that by moving the middleware to ParentSchema which has access to itself and its children:

ParentSchema.pre('save', function(next){
    var parent = this;
    this.child.forEach(function(child) {
        child.name = parent.name;
    });
    next();
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471