0

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?

Community
  • 1
  • 1
CSharp
  • 1,396
  • 1
  • 18
  • 41

1 Answers1

1

Well you are defining two different collections, Child and Parent in ->

var Parent = db.model('Parent', parent);

var Child = db.model('Child', child);

So you are free to user the Child model as you like by doing add/remove/update. By saving it as a 'ref' you can do:

Parent.find({_id:'idofparent'})
.populate('children')
.exec((err, result) => { .... } )

Your Parent will then be populated with their children.!

raubas
  • 674
  • 7
  • 6
  • Thanks! So if I understand, by keeping the refs in an array I can retrieve them by calling `populate` rather than retrieving each child with a query on the child model. But other than that, there's no reason to maintain a child array.. – CSharp Nov 01 '16 at 14:15
  • 1
    Yep, populate does those queries for you so very convenient if you want to retrieve a parents all children :) – raubas Nov 02 '16 at 11:45
  • Great! Thanks for the clarification – CSharp Nov 02 '16 at 12:17