猫鼬 - 我应该在父文档,子文档或两者中添加引用吗?

时间:2016-11-29 23:22:31

标签: mongodb mongoose schema

我必须使用mongodb集合,我们称之为parentschildren。这个父母/孩子的设计有一对多的关系,当我查询父母时我也想要孩子。按照这种逻辑,有这种模型设计是有道理的:

var ParentSchema = new Schema({
    name: String,
    children: [{type: Schema.Types.ObjectID, ref: 'Child'}]
});

var ChildSchema = new Schema({
    name: String
});

这样,我可以使用populate()轻松地让孩子与父母一起。但是,我被告知使用这样的阵列并不好,因为它们可能会变得混乱。所以,如果我将对象引用放在ChildSchema中,那么我可以避免使用这样的数组。

var ParentSchema = new Schema({
    name: String
});

var ChildSchema = new Schema({
    name: String,
    parent: {type: Schema.Types.ObjectID, ref: 'Parent'}
});

但如果我想让孩子再次与父母同在,populate()不会工作。什么是最好使用的模式,如果我在孩子中使用refs,是否有类似populate()的方法可以做到这一点?我不想做查询以获得一个结果。

1 个答案:

答案 0 :(得分:5)

我的理解是,存在一系列对父母中的儿童的引用的问题将是儿童数组无限制的情况。如果不是这种情况,我认为在父母中存储一系列参考文献是推荐的模式。如果孩子的数量非常大或无限制,那么文档建议使用Virtuals。

我相信一个简单的例子看起来像......

`
var ChildSchema = new Schema({
      name: String,
      parent: String
});

var ParentSchema = new Schema({
       name: String
});

ParentSchema.virtual('children', {
      ref: 'Child',   // the model to use
      localField: 'name',  // find children where 'localField' 
      foreignField: 'parent' // is equal to foreignField
});


var Parent = mongoose.model('Parent', parentSchema);
var Child = mongoose.model('Child', childSchema);

/*
 Let's say we have two parents: Jack and Mindy
 And four children: Jake with Jack, and Mike, Molly, and Mildred with Mindy
*/

Parent.find({}).populate('children').exec(function(error, parents) {
/// parents.children is now an array of instances of Child. 
});

`

有关人口的更多信息,请查看Mongoose.js文档mongoosejs.com

所有归功于mongoosejs.com作为我的例子只是他们的改编。 此外,请注意我没有实际测试此代码,因为我在手机上回答了这个问题。

希望这会有所帮助。

相关问题