Reputation: 153
i'm trying to create a database which has some parent and each parent has it`s children. The children count may be more than 10000.
what is the best way to design a database like this?
should i create just one collection for parent and then create a document for each parent and put children inside it? like this:
const ParentSchema = new mongoose.Schema({
...Parent,
children: [ChildSchema] // put children here??
});
mongoose.model('parent',ParentSchema);
or create one collection for parent and one collection for children and reference each child to it`s own parent? like this:
const ParentSchema = new mongoose.Schema({
...Parent
});
const ChildSchema = new mongoose.Schema({
...Child,
parentId: {
type: mongoose.Types.ObjectId,
ref: 'parent'
}
});
mongoose.model('parent',ParentSchema);
mongoose.model('child',ChildSchema);
or another way to design?
thanks.
Upvotes: 0
Views: 1073
Reputation: 445
Frankly, depends upon use case.
First case might work with with small child object size, although the number 10000 is fairly large. Think in terms of total size of a parent object fetched. If the child is of meaningful size, say c
bytes, the total size of parent immediately becomes c*10000
bytes.
Second approach should work with small number of child objects. Obvious limitation is you might end up fetching 10,000 objects apart from the parent object. So it might be slower. Also, it is limited in terms of fetching all child objects with a given parent, unless you start indexing parentId as well. If the count of child object scales, it might cause increased memory usage due to multiple indexes being maintained.
Another approach can be saving childIds in the array of the parent, and then fetch them separately from an child collection indexed on _id
. Also, have the child object store the parentId as well. This way, we can answer the following in good enough time if the need be:
As the fetching could be slow, I would rather recommend a paginated load. We can also store some other attribute of the child object along side the childId in the parent object. This can help to fetch just the right amount of information from the parent, and we can then get full child object if required.
const ParentSchema = new mongoose.Schema({
...Parent,
childIdArr: [{ childId: ObjectId, name: extraAttribute }]
});
const ChildSchema = new mongoose.Schema({
...Child,
parentId: ObjectId,
});
mongoose.model('parent',ParentSchema);
mongoose.model('child',ChildSchema);
Upvotes: 1