fzaninotto / mongoose-lifecycle

Plugin for Mongoose (Node.js ODM for MongoDB) adding lifecyle events on the model class
MIT License
94 stars 9 forks source link

Usage when adding subdoc to nested array #6

Open murphman300 opened 7 years ago

murphman300 commented 7 years ago

I have a model which has the following structure:

submodel = new mongoose.Schema({
     value : {type: String, require: true}
});

model = new mongoose.Schema({
     values : {type: [submodel], require: true},
     data : {type: String, require: true}
});

document = new mongoose.Schema({
    models :  {type: model, require: true},
});

I do know how to listen to events with this library for the document, but what i'm interested in is updating 'data' inside of 'model', whenever a 'submodel' is added to 'values'.

I thought of adding a listener to 'submodel', but i can't seem to figure out how to have access to it's parent 'model' that way..

Would the better approach be to put a 'afterSave' listened on the 'model' schema, and just re-calculate its 'values' everytime?

Please let me know if there's a better way than the latter or if i'm not clear enough with my example!

Cheers,