Skip to content

Instantly share code, notes, and snippets.

@navanathjadhav
Created June 26, 2022 13:00
Embed
What would you like to do?
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