19. Database, Schema & Models | Mongoose

- First of all create a cluster(collection of databases) on mongoDB Atlas and connect it to mongoDB compass at your computer by following these steps:-
1. Create a Cluster on MongoDB Atlas
Step 1: Sign up/Log in
Go to the MongoDB Atlas website.
Sign in with your existing account or sign up for a free account.
Step 2: Create a Cluster
After logging in, click on "Build a Cluster" or "Create a Cluster".
Choose the Cluster Type: For free-tier, select Shared Cluster (M0).
Select a Cloud Provider and Region:
Choose a cloud provider (AWS, Azure, or Google Cloud).
Select a region close to your application or your physical location for better performance.
Configure Cluster: Leave the default settings for a free-tier cluster.
Create Cluster: Click "Create Cluster" and wait for it to be provisioned (takes ~5-10 minutes).
2. Configure Cluster Access
Step 3: Add a Database User
Go to the Database Access section under "Security" in the left-hand menu.
Click "Add New Database User".
Set:
Authentication Method: Username/Password.
Username: Create a unique username.
Password: Create a strong password.
Assign the user role: Choose Atlas Admin (for full access during setup).
Click "Add User".
Step 4: Add Your IP Address
Go to the Network Access section under "Security".
Click "Add IP Address".
Add your local IP address:
To allow your current IP, click "Add Current IP".
To allow all IPs, enter
0.0.0.0/0
(not recommended for production).
Click "Confirm".
3. Get Connection String
Step 5: Retrieve the Cluster Connection String
Go to the Clusters section in Atlas.
Click "Connect" for your cluster.
Select "Connect using MongoDB Compass".
Copy the connection string (e.g.,
mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>
).
Replace <username>
and <password>
with the credentials you created earlier.
4. Download and Install MongoDB Compass
Step 6: Install MongoDB Compass
Download MongoDB Compass from the official site.
Install it by following the instructions for your operating system.
5. Connect to MongoDB Atlas using Compass
Step 7: Set up Connection in Compass
Open MongoDB Compass.
In the "New Connection" window:
Paste the connection string you copied earlier.
Replace
<username>
and<password>
with your database user credentials.
Click "Connect".
6. Verify Connection
After successful connection, you’ll see a list of databases in the Compass interface. You can now create, read, update, or delete documents and collections.
To know and set up your IP address in your network access tab in atlas in cmd write this command and press enter “curl -4 ifconfig.me“ your id will be prompted then add it to network access.
Now add a “config“ folder inside src folder, this config folder is for adding any configuration.
inside config create a file “database.js“ here we will write a logic to connect DB
we will use npm package known as mongoose (which is used to connect your application with mongoDB) by executing command “npm i mongoose“
//database.js const mongoose = require("mongoose"); mongoose.connect( "....connectionString.../dbName" );
above is not a write way to connect DB as it return a promise and it is a async connection
right way is this
const mongoose = require("mongoose"); const connectDB = async () => { await mongoose.connect( "....connectionString.../dbName(i have taken practice as database name)"// this is "cluster + dbName" ); }; connectDB() .then(() => { console.log("connected to DB"); }) .catch((err) => { console.error("not connected DB"); });
above code still doesn’t connect Why because we have to include this code inside app.js file by require(“./config/database“) and also keep in mind that right way is to first connect application to DB and then do app.listen() or start server because if we don’t do this then if someone do app.listen() or start server first, make API call from DB and still DB doesn’t connected this will be a problem.
const mongoose = require("mongoose"); const connectDB = async () => { await mongoose.connect( "....connectionString.../dbName"// this is "cluster + dbName" ); }; module.exports= connectDB;
//app.js const express = require("express"); const app = express(); const port = 3000; const connectDB = require("./config/database"); connectDB() .then(() => { console.log("connected to DB"); app.listen(port, () => { console.log(`Server is running on port ${port}`); }); }) .catch((err) => { console.error("not ok some error"); });
in console we get
Creating Schema
Schema is identity for collection(table) document, it is basically about what type of information we want to store with legit field name.
we read schema from mongoose
after creating schema we create model, we can create multiple instances by using model as SchemaName. For example User table using userSchema, Friend table using same userSchema etc.
for example:- mongoose.model(“Name of model“, SchemaName)
mongoose.model(“user“,userSchema);//user is table name
name with capital letter of model name depicts model like classes.
Now create models folder inside src and in models create user.js schema
//user .js
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
firstName: {
type: String,
},
lastName: {
type: String,
},
email: {
type: String,
},
password: {
type: String,
},
City: {
type: String,
},
});
const User = mongoose.model("User", userSchema);
module.exports = User;
//creating schema for User table
creating a POST API to add data to Database
Note:- All the operation related to database whether it is like fetching data from database or sending data to database and many other operation are all asynchronous in nature and they return promise so always perform these operation in async…await syntax and use try….catch block to handle error gracefully.
// app.js const express = require("express"); const app = express(); const port = 3000; const connectDB = require("./config/database"); //getting DB connection const User = require("./models/user"); //getting User model app.post("/user", async (req, res) => {// POST API to save data to DB const user = new User({ ///creating a new Instance of User model firstName: "faraz", lastName: "alam", email: "test@123.com", password: "test@123", City: "Pune", }); try { await user.save(); res.send("user addedd sucessfully"); } catch (err) { res.status(400).send("error saving the data:- " + err.message); } }); connectDB() .then(() => { console.log("connected to DB"); app.listen(port, () => { console.log(`Server is running on port ${port}`); }); }) .catch((err) => { console.error("Not connected to DB"); });
when “POST …/user“ get hit in postman data save to database.
One thing to note that in database “practice“ is database name, “users“ is collection or table name although we have created schema for “User“ table but in database database and collection name is usually stored in small and plural form. And the table like thing which have different field is called as “document“, we can create multiple documents in a “users” collection by altering data in POST API . There is unique field known as “_id“ which is created automatically by mongoDB for us, however we can also enter this “_id“ manually but it suggested by mongoDB not to do so.
Notes:- If You get this error “OPEN:SSL Internal……Port 80…..“ while sending data to database you can check out this video.
Subscribe to my newsletter
Read articles from Faraz Alam directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Faraz Alam
Faraz Alam
Assalamualaikum warahmatullah wabarakatuh( traditional Islamic greeting in Arabic "Assalamu alaikum": "Peace be upon you." "Wa rahmatullahi": "And the mercy of Allah." "Wa barakatuh": "And His blessings.") I’m Faraz Alam, and I’m documenting my journey through the world of software technology. Despite earning a master’s degree in Computer Applications and having access to opportunities provided by my tier-3 college, I struggled to take full advantage of them due to poor management and a less productive environment. This led to joblessness, primarily due to a lack of upskilling. Now, I am dedicated to enhancing my skills and knowledge with the aim of securing a valuable job offer from leading product-based companies, including those in the FAANG group (Facebook, Amazon, Apple, Netflix, Google) and other prominent tech giants. This documentation is not for self-promotion; rather, it is for anyone who is waiting for an opportunity but feels they lack the tools and skills required to overcome challenges. It’s a testament to the effort and responsibility needed to navigate the journey towards success when you take charge of your own path. Date: 31 July 2024, 07:25 AM This page will be updated regularly to reflect new achievements and milestones as I continue to build my career.