Skip to content

Instantly share code, notes, and snippets.

@navanathjadhav
Created June 26, 2022 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navanathjadhav/a8a2bd32bba70dd93299fe39fed89a1b to your computer and use it in GitHub Desktop.
Save navanathjadhav/a8a2bd32bba70dd93299fe39fed89a1b to your computer and use it in GitHub Desktop.
Example of SQL & MongoDB way DB design
/*
* 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