I have two mongodb collections, let's call them parents
and children
. This parents/children design has a one-to-many relationship, and when I query the parent I want the children as well. It makes sense to have this model design:
var ParentSchema = new Schema({
name: String,
children: [{type: Schema.Types.ObjectID, ref: 'Child'}]
});
var ChildSchema = new Schema({
name: String
});
That way, I can use populate()
to easily get the children within the parent. However, I've been told that it's not good to use arrays like this, because they can get cluttered. So, if I put the object reference in the ChildSchema
, then I can avoid using an array like that.
var ParentSchema = new Schema({
name: String
});
var ChildSchema = new Schema({
name: String,
parent: {type: Schema.Types.ObjectID, ref: 'Parent'}
});
But if I want to get the children withing the parent again, populate()
won't work. What's the best pattern to use, and if I'm using refs in the children, is there a method similar to populate()
that does this? I don't like having to make two queries to get one result.