Backend — Data Modelling for the backend with Mongoose.

Rushabh Dabhade
5 min readNov 15, 2023

--

Data Modelling for the backend with Mongoose.

Mongoose

Mongoose is an Object-Data Modeling (ODM) library for MongoDB, a popular NoSQL database. An ODM is a tool or library that provides a higher-level abstraction for working with databases, making it easier for developers to interact with a database using the JavaScript programming language. In the case of Mongoose, it’s specifically designed for working with MongoDB.

Mongoose provides a schema-based data modeling system, which allows you to define the structure of your data using a schema, and then use that schema to create and query documents in your MongoDB database.

Tools we are using -

Moon modeler (for Data Modeling) — paid

Eraser.io (for Data Modeling) — free

Online IDE —

What is data modeling?

Data modeling is a process in which the structure, organization, and relationships of data are defined and documented to facilitate effective data management and information retrieval. It is an essential step in designing and developing a database or information system, and it helps ensure that data is structured in a way that accurately represents the real-world entities and relationships it represents.

Key aspects of data modeling include:

  1. Entities: Data modeling identifies the entities or objects that need to be represented in the system. These entities can be physical (e.g., products, customers, employees) or conceptual (e.g., orders, invoices, reservations).
  2. Attributes: For each entity, data modeling defines the attributes or properties that describe the entity. For example, a “Customer” entity might have attributes like “Name,” “Address,” and “Phone Number.”
  3. Data Types: Data modeling specifies the data types for each attribute, indicating the kind of data (e.g., text, numbers, dates) that an attribute can hold.

Data Modeling for Todo App

We are creating a Data modeling for the Todo app, with three fields, User, Todo, and Sub Todo.

Firstly, make three files (user.models.js, todo.models.js, sub_todo.models.js) in the models/todo directory.

And install the mongoose package.

npm i mongoose

Creating a boilerplate code,

user.models.js

import mongoose from "mongoose"

const userSchema = new mongoose.Schema({})

export const User = mongoose.model("User", userSchema)

Here, you are creating a new Mongoose schema named userSchema using mongoose.Schema(). A schema is a blueprint that defines the structure and constraints for your MongoDB documents (in this case, documents representing users).

In this line, you are creating a Mongoose model named “User” using the mongoose.model() method. The mongoose.model() method takes two arguments:

  • The first argument is the name you want to use for the model. In this case, it’s “User.”
  • The second argument is the schema you want to associate with the model, which is userSchema we defined earlier.

The model “User” is now associated with the “User” schema, and you can use it to perform various database operations on user data.

We can define data by specifying the fields and their data types within the object passed to mongoose.Schema

const userSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
unique: true,
lowercase: true,
},
email: {
type: String,
required: true,
unique: true,
lowercase: true
},
password: {
type: String,
required: [true, "Password is required"]
}
}

timestamps

In Mongoose, you can enable automatic timestamps for your MongoDB documents by setting the timestamps option in your schema. Enabling timestamps adds two fields, createdAt and updatedAt, to your documents, which automatically store the creation and update timestamps when you create or modify a document. This is a convenient way to track when data was added or last updated.

Here’s how you can enable timestamps in a Mongoose schema:

const userSchema = new mongoose.Schema(
{ .....
}, {timestamp: true}
)

Reference to another model

In Mongoose, you can establish relationships between different data models using references. This is a powerful feature that allows you to connect documents in different collections, providing a way to represent associations between data.

In the Todo app, we are giving sub-todos for the given Todo. To pass this reference,

todo.models.js

const todoSchema = new mongoose.Schema({
content: {
type: String,
required: true,
},
complete: {
type: Boolean,
default: false
},
createdBy: {
type: mongoose.Schema.Type.ObjectId,
ref: "User"
},
subTodos: [
{
type: mongoose.Schema.Type.ObjectId,
ref: "SubTodo"
}
] //Array of Sub-Todos
}

Another Example of Data Modeling:

Data modeling for E-commerce

user.models.js

const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
lowercase: true
},
email: {
type: String,
required: true,
unique: true,
lowercase: true
},
password: {
type: String,
required: true
},
}, {timestamp: true})
product.models.js

const productSchema = new mongoose.Schema({
description: {
required: true,
type: String
},
name: {
required: true,
type: String
},
productImage: {
type: String
},
price: {
type: Number,
default: 0
},
category: {
type: mongoose.Schema.Types.ObjectId,
ref: "Category"
},
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: "Seller"
}
},
{timestamp: true}

})
order.models.js

const orderItemSchema = new mongoose.Schema({
productId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Product"
},
quantity: {
type: Number,
required: true
}
})

const orderSchema = new mongoose.Schema({
orderPrice: {
type: Number,
required: true
},
customer: {
type: mongoose.Schema.Type.ObjectId,
ref: "User"
},
orderItems: {
type: [orderItemSchema]
},
status: {
type: String,
enum: ["PENDING", "CANCELLED", "DELIVERED"],
default: "PENDING"
}
}, {timestamp: true})

In conclusion, mastering data modeling is paramount for any backend developer navigating the dynamic landscape of MongoDB with Mongoose. This article delved into the intricate art of crafting robust data models, offering a comprehensive guide for both beginners and seasoned developers.

As you embark on your backend development journey, remember that data modeling is not just a technical task; it’s an art that requires thoughtful consideration of your application’s unique requirements. With Mongoose as your ally, you’re well-positioned to navigate the intricate landscape of MongoDB, turning your data structures into a robust foundation for seamless, performant applications.

Happy coding!

--

--

Rushabh Dabhade

Full Stack Developer | Building Beautiful Apps | Freelancer | Exploring the world of tech