2. Data Modeling
Here's a version with proper Markdown formatting:
Mongoose Basics
npm i mongoose
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It simplifies interactions with MongoDB by providing a structured way to define data schemas, models, and perform CRUD (Create, Read, Update, Delete) operations.
basic syntax architechture
import mongoose from "mongoose"
const uerSchema = new mongoose.schema({})
export const User = mongoose.model("User",userSchema)
Good Practices with Mongoose
- Define Schema Types and Validation: Always define field types and include validation to ensure data consistency.
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, min: 0 },
});
Model Naming and Pluralization in Mongoose
When you define a model in Mongoose, it automatically pluralizes and lowercases the model name to create the collection name in MongoDB. For example:
const User = mongoose.model('User', userSchema);
This will result in a collection named users, not User. Mongoose uses lowercase and plural for collections by default, so:
UserbecomesusersPersonbecomespeople
1. ToDo App: Data Flow Diagram
To begin working with databases, it’s essential to map out the data flow in your backend, including interactions with the database.

2. Creating the Data Models
User Model
import mongoose from 'mongoose';
const { Schema } = mongoose; // imported Schema from mongoose
// so no need to write mongoose.Schema each time
const userSchema = new Schema(
{
username: {
type: String,
required: [true, "it is a required field"],
unique: true,
lowercase: true
},
password: {
type: String,
required: [true, "it is a required field"],
min: [5, "Password too short"],
max: [15, "Password may not exceed 15 characters"]
},
email: {
type: String,
required: [true, "it is a required field"],
unique: true,
lowercase: true
}
},
{ timestamps: true }
);
const User = mongoose.model('User', userSchema);
export default User;
Todo Model
import mongoose from 'mongoose';
const todoSchema = new mongoose.Schema(
{
content: {
type: String,
required: true,
},
completeCheck: {
type: Boolean,
default: false
},
createdBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
subTodo: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "subTodo"
}
]
},
{ timestamps: true }
);
const Todo = mongoose.model("Todo", todoSchema);
export default Todo;
SubTodo Model
import mongoose from 'mongoose';
const subTodoSchema = new mongoose.Schema(
{
content: {
type: String,
required: true
},
completeCheck: {
type: Boolean,
default: false
}
},
{ timestamps: true }
);
const SubTodo = mongoose.model("SubTodo", subTodoSchema);
export default SubTodo;
Each section is now formatted to improve readability, and the model names have been capitalized for consistency with Mongoose model naming conventions.