简体   繁体   中英

Correct way to use array of sub documents in Mongoose

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?

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.!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM