Example of SQL & MongoDB way DB design
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* SQL way design | |
* Comment schema is separate from post schema | |
* If you have to perfrom critical operations on comments then this is suitable option, | |
* but if you will be performing simple operations like CRUD, you can keep comments in post schema | |
* Con: You have to write seprate query to fetch comments and it will cause extra burden | |
*/ | |
/* | |
* Post Schema | |
*/ | |
const postSchema = new Schema({ | |
createdBy: { | |
type: Schema.Types.ObjectId, | |
ref: "User", | |
}, | |
heading: String, | |
description: String, | |
}); | |
/* | |
* Comment Schema | |
*/ | |
const commentSchema = new Schema({ | |
createdBy: { | |
type: Schema.Types.ObjectId, | |
ref: "User", | |
}, | |
post: { | |
type: Schema.Types.ObjectId, | |
ref: "Post", | |
}, | |
text: String, | |
}); | |
/* | |
* MongoDB way design | |
* Comment schema is combined into post schema | |
* It will be difficult to perform critical operations on comments | |
* This is best suitable way, if you will be performing simple operations on comments like CRUD | |
* Pro: You can get everything in one single query | |
*/ | |
/* | |
* Post Schema with comments | |
*/ | |
const postSchema = new Schema({ | |
createdBy: { | |
type: Schema.Types.ObjectId, | |
ref: "User", | |
}, | |
heading: String, | |
description: String, | |
comments: [ | |
{ | |
createdBy: { | |
type: Schema.Types.ObjectId, | |
ref: "User", | |
}, | |
text: String, | |
}, | |
], | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment