Riv
Riv

Reputation: 357

Proper way to organize data models in a MEAN stack application

I am making an MEAN stack app and use Mongoose alongside Mongo. I am struggling with organizing my objects in database. All works as expected but I have a feeling that the way I am doing things is wrong, but can't seem to find any resources on the topic that could help me, thus I hope somebody with some experience can share it with me.

I use Mongoose to create several schemas, and there is one dilemma I am facing, concerning nested objects in MongoDB. Let's say I have a model that looks like that:

ParentSchema:{
    property1:String,
    children:[{}]
}

So, property1 is just some string, 'children' is an array that will contain objects of type 'Child' with some other properties, but also another array (f.ex. 'grandchildren:[{]} ), this time with another type of objects (Grandchild).

Child and Grandchild have no schemas and do not exist outside of the Parent, and will most likely be unique to each instance of Parent, so two Parents would not be sharing a Child object.

In my app, I am able to use urls such as '/parent/:id1/Child/:id2/Grandchild/:id3', where 'id1' is an actual id of Parent that Mongo generates, while 'id2' is an index of Child object instance stored in Parents array. The same goes for instances of Grandchildren stored inside Child object.

I was thinking that maybe having separate schemas for all 3 objects, and just saving references to objects is the way to go, like this:

ParentSchema:{
    prop1:String,
    children:[{type:ObjectId, ref:'Child'}]
}
ChildSchema:{
    prop1:String,
    granchildren:[{type : ObjectId, ref: 'Grandchild'}]
 }
GrandChildSchema:{
    prop1:String,
    prop2:String
}

..but was unsure, as for me it implies that Child and GrandChild instances would be shared between different parents, however it seems easier to work with.

To sum up, I would like to know is:

I apologize if the question is somehow weird, I will try to clarify as best as I can if required.

Upvotes: 0

Views: 85

Answers (1)

Muli Yulzary
Muli Yulzary

Reputation: 2569

I would go with the second approach for a couple of reasons:

  1. Schemas have better readability in my opinion.
  2. They allow for data validation which you lack in the first approach.

Please note the answer below is primarily opinion based.

For the API design:

I think its really up to you as to which paths to expose to the consumer, since you've stated Child and Grandchild do not have the right to exist without a parent - I think your routes are fine as they are.

And finally - your process for creating these entities look fine to me. I would do the same thing myself.

Upvotes: 1

Related Questions