I'm just learning Mongoose, and I have modeled Parent and Child documents as follows..
var parent = new Schema({
children: [{ type: Schema.Types.ObjectId, ref: 'Child' }],
});
var Parent = db.model('Parent', parent);
var child = new Schema({
_owner: { type: Schema.Types.ObjectId, ref: 'Parent' },
});
var Child = db.model('Child', child);
When I remove the Parent I want to also remove all the Child objects referenced in the children field. Another question on Stackoverflow states that the parent's pre middleware function can be written like this...
parent.pre('remove', function(next) {
Child.remove({_owner: this._id}).exec();
next();
});
Which should ensure that all child objects are deleted. In this case, however, is there any reason to have the children array in the Parent schema? Couldn't I also perform create/read/update/delete operations without it? For example, if I want all children I could do?
Child.find({_owner: user._id}).exec(function(err, results) { ... };
All examples I've seen of Mongoose 'hasMany' relations feature a 'children' array though but don't show how it is then used. Can someone provide an example or give a purpose for having it?