简体   繁体   English

在Mongoose中使用子文档数组的正确方法

[英]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.. 我正在学习猫鼬,并且已按如下所示对“ Parent Child文档进行了建模。

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. 当我删除Parent我还要删除children字段中引用的所有Child对象。 Another question on Stackoverflow states that the parent's pre middleware function can be written like this... 关于Stackoverflow的另一个问题指出,可以像这样编写父级的中间件pre功能...

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? 但是,在这种情况下,是否有任何理由要在Parent模式中拥有children数组? 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. 我见过的所有有关Mongoose'hasMany'关系的示例都具有一个'children'数组,但是没有显示如何使用它。 Can someone provide an example or give a purpose for having it? 有人可以提供示例或给出示例吗?

Well you are defining two different collections, Child and Parent in -> 好吧,您在->中定义了两个不同的集合,Child和Parent

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. 因此,您可以通过添加/删除/更新来随意使用Child模型。 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.! 然后,您的父母中将会有他们的孩子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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