JenuRudan
JenuRudan

Reputation: 545

Mongo - 1 to many -Database Modeling

I'm using mongodb. my models are factory,style,process

Style has a factory

Process has a style

so it's 1 to many relationship between factory and style, style and process

Process Model

name:{
    type: String,
    required: true,
},
style: {type:Schema.Types.ObjectId,ref:'Style'}

Style Model

code:{
    type: String,
    required: true,
    unique: true
},
factory: {type:Schema.Types.ObjectId,ref:'Factory'},

the issue is when their is a lot of documents, 1000factory ->styles->processes

find the styles for a specific factory will take a lot of time, same for processes for a specific style

so is it better to add an array of refs in style for it's processes and same for factory to add an array of refs for styles ?

if so, should i remove style ref in process or it's ok to leave ?

would it affect storage only ? or performance too ?

Upvotes: 0

Views: 33

Answers (1)

cop
cop

Reputation: 603

  • First of all, Yes it will affect the performance issue because at one place your are getting all ID'S of Factories if your put in an Array by finding JUST one Style Document and other place you have to get all the factories whose style Id is 5q1q1q2q21q2q12q1 (EXAMPLE).

So it will go to all the same style id's and get all the factories and other side you Just get the one style model and get all the factories by populate (of mongoose) or lookup ( of MongoDB Aggregate) which ever you choose.

  • Second, in saving Ref's in Array in model will obviously increase little memory because at other side you saving just one reference

Upvotes: 3

Related Questions