【问题标题】:Correct way to use array of sub documents in Mongoose在 Mongoose 中使用子文档数组的正确方法
【发布时间】:2016-10-31 23:27:03
【问题描述】:

我刚学Mongoose,已经对ParentChild文档建模如下..

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);

当我删除 Parent 时,我还想删除 children 字段中引用的所有 Child 对象。 Stackoverflow 上的Another question 声明父级的pre 中间件函数可以这样写...

parent.pre('remove', function(next) {
  Child.remove({_owner: this._id}).exec();
  next();
});

这应该确保所有子对象都被删除。但是,在这种情况下,是否有任何理由在 Parent 模式中包含 children 数组?没有它我不能执行创建/读取/更新/删除操作吗?例如,如果我想要所有可以做的孩子?

Child.find({_owner: user._id}).exec(function(err, results) { ... };

我见过的所有关于 Mongoose 'hasMany' 关系的示例都具有一个 'children' 数组,但没有显示它是如何使用的。有人可以提供一个例子或给出一个目的吗?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    好吧,您在 ->

    中定义了两个不同的集合,Child 和 Parent

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

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

    因此,您可以通过添加/删除/更新随意使用 Child 模型。通过将其保存为“参考”,您可以:

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

    然后您的父母将被他们的孩子填充。!

    【讨论】:

    • 谢谢!因此,如果我理解的话,通过将参考保存在一个数组中,我可以通过调用populate 来检索它们,而不是通过对子模型的查询来检索每个子。但除此之外,没有理由维护子数组..
    • 是的,如果您想检索所有孩子的父母,那么填充这些查询会非常方便:)
    • 太棒了!感谢您的澄清
    猜你喜欢
    • 2014-04-21
    • 2017-09-17
    • 2020-01-02
    • 2018-01-26
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多