Day 5 - 60 Days of Learning 2025


Connecting to Database and Creating User Types and Model
On June 5, 2025, I worked on connecting my Express server with MongoDB which was running on docker container. I used docker image of MongoDB so that I can use it locally and don’t have to install MongoDB separately in my system. I can just spin up a docker image of MongoDB, pass some environment variables and can connect to it using my project or from VS Code MongoDB extension for testing.
The GitHub link for the repository of beats-backend service.
Spinning Up MongoDB
I used docker image and docker compose for spinning up a MongoDB container.
Why Docker?
Because it is easier to spin any database without much hassle we have configure a docker compose yaml file and pass on some environment variables of initial setup and we can connect to the MongoDB using our express app or any other library/tool/extension, I used VS Code's MongoDB extension for testing the setup.
Inside compose.yml
file
services:
mongo:
image: mongo
container_name: mongodb
restart: unless-stopped
ports:
- 27017:27017
environment:
- MONGO_INITDB_ROOT_USERNAME=<db_name>
- MONGO_INITDB_ROOT_PASSWORD=<db_password>
volumes:
- ./db/data:/data/db
Creating Function for Connecting to Database
A function for connecting to the MongoDB database that was running on docker.
import { config } from "dotenv";
import mongoose from "mongoose";
// Accessing environment variables
config();
const dbHost = process.env.DB_HOST;
const dbPort = process.env.DB_PORT || 27017;
const dbUsername = process.env.DB_USERNAME;
const dbPassword = process.env.DB_PASSWORD;
const dbName = process.env.DB_NAME;
// Database connection string
const connectionString = `mongodb://${dbUsername}:${dbPassword}@${dbHost}:${dbPort}/?authSource=admin`;
async function connectDatabase() {
try {
await mongoose.connect(connectionString, { dbName });
console.log("Connected to the database successfully");
} catch (error) {
console.error("Failed to connect to the database:", error);
process.exit(1);
}
}
export { connectDatabase };
Imported that function and used it inside the index.ts
file
import { config } from "dotenv";
import { app } from "./app";
import { connectDatabase } from "./database";
// Accessing environment variables
config();
const port = process.env.PORT || 5000;
// Running the server
connectDatabase()
.then(() => {
app.on("error", (error) => {
console.error("Failed to start the server", error);
process.exit(1);
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
})
.catch((error) => {
console.error("Failed to connect to the database:", error);
});
User Types and Model
Types for user helps in writing better type safe code and gives auto complete suggestions when writing code. Both are great.
Inside types/user.type.ts
file
import mongoose from "mongoose";
export interface UserType {
_id: mongoose.Types.ObjectId;
name: string;
email: string;
fullName: string;
password: string;
avatar: string;
coverImage?: string;
role: "user" | "artist";
refreshToken?: string;
createdAt: Date;
updatedAt: Date;
}
export type CreateUserType = Omit<
UserType,
"_id" | "createdAt" | "updatedAt"
> & {
role?: "user" | "artist";
};
export type UpdateUserType = Partial<
Omit<UserType, "_id" | "createdAt" | "updatedAt">
>;
export type UserResponseType = Omit<UserType, "password" | "refreshToken">;
Then created User model with these user types.
Inside models/user.model.ts
file
import mongoose from "mongoose";
import { UserType } from "../types/user.type";
// Email validator regex
const emailValidatorRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const userSchema = new mongoose.Schema<UserType>(
{
name: {
type: String,
required: [true, "Username is required"],
trim: true,
unique: true,
lowercase: true,
index: true,
},
email: {
type: String,
required: [true, "Email is required"],
trim: true,
unique: true,
lowercase: true,
index: true,
match: [emailValidatorRegex, "Please enter a valid email"],
},
fullName: {
type: String,
required: [true, "Fullname is required"],
trim: true,
},
password: {
type: String,
required: [true, "Password is required"],
trim: true,
},
avatar: {
type: String,
required: [true, "User avatar is required"],
},
coverImage: {
type: String,
},
role: {
type: String,
enum: ["user", "artist"],
required: true,
default: "user",
},
refreshToken: {
type: String,
},
},
{ timestamps: true }
);
export const User = mongoose.model<UserType>("User", userSchema);
I asked Claude for the email validator Regex.
Testing The Setup
After this I created basic controller for creating a new user and tested the setup. The controller needs more work but right now it worked for correctly and created a new user. I tested the /api/v1/user/create
endpoint using VS Code’s Postman extension.
Going to work on user controller after this.
Subscribe to my newsletter
Read articles from Ashmin Bhujel directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ashmin Bhujel
Ashmin Bhujel
Learner | Software Developer | TypeScript | Node.js | React.js | MongoDB | Docker