DEV Community

Discussion on: Designing a better architecture for a Node.js API

 
lalwanikamaldev profile image
lalwanikamaldev

Any Idea ?

Thread Thread
 
pacheco profile image
Thiago Pacheco

Hello there,
Sorry for the delay, I thought I had answer you already.

You could basically define a comments attribute into your post schema with a reference for this comment schema, like so:

{
 ...your attributes
  comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]
});
Enter fullscreen mode Exit fullscreen mode

Then when you query this post, you can use the populate method from mongoose to retrieve the comments.

Post.
  findOne({ title: 'title' }).
  populate('comments')
Enter fullscreen mode Exit fullscreen mode

Here is the link with the docs about how you can implement a relationship one-to-many.
mongoosejs.com/docs/populate.html

Thread Thread
 
pacheco profile image
Thiago Pacheco

But remember that this is not the same concept of joining as in SQL, in MongoDB you don't have this concept of relationship.
The relationship is defined by code, with your schemas and the extra validations you are supposed to create based on your necessities.

Here is some more information about the key differences between NoSQL and SQL:
mongodb.com/nosql-explained/nosql-...