Skip to main content

Command Palette

Search for a command to run...

How to connect MongoDB atlas in Node.js

Updated
2 min read
How to connect MongoDB atlas in Node.js

Here's a step-by-step guide on how to connect MongoDB Atlas with Mongoose in a Node.js project:

  1. Sign up for an MongoDB Atlas account if you don't already have one and create a new cluster.

  2. Navigate to the "Connect" button in your cluster and choose "Connect your application".

  3. Select the driver (Node.js) and version you are using.

  4. Copy the connection string that is provided, it should be in the format of mongodb+srv://&lt;username&gt;:&lt;password&gt;@</mark>[<mark>cluster-name.mongodb.net/test</mark>](http://cluster-name.mongodb.net/test)<mark>

  5. In your Node.js project, install Mongoose using npm: npm install mongoose

  6. Require Mongoose in your project and connect to the MongoDB Atlas cluster by pasting the connection string into the connect method:

     //app.js
     const express = require('express');
     const mongoose = require('mongoose');
     const app = express();
    
     try {
         mongoose.connect('<connection string>');
         console.log('DB is connected!')
     } catch(error){
         console.log(error)
     }
    
  7. You are now connected to MongoDB Atlas and can start using Mongoose to perform database operations on your collections.

Note: Replace <connection string> with the actual connection string, you copied from MongoDB Atlas.


Create use schema:

  1. Define a schema for the user document using the mongoose.Schema method:

     const Schema = new mongoose.Schema({
       name: { type: String, required: true },
       email: { type: String, required: true, unique: true },
       password: { type: String, required: true },
     });
    
  2. Create a Mongoose model from the schema using the mongoose.model method:

     const User = mongoose.model('User', Schema);
    
  3. You can now perform database operations on the User model, such as inserting new documents, finding, updating, or deleting documents, etc.

Let's take look at our setup:

For the final project, you should use separate files/modules for each category-based operation.

const express = require("express");
const mongoose = require("mongoose");
const app = express();
//MongoDB and Mongoose

require("dotenv").config(); 
const uri = process.env.DB; 

mongoose.connect(uri, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true,
});

//DB conections
try {
    mongoose.connect('<connection string>');
    console.log('DB is connected!')
} catch(error){
    console.log(error)
}

const schema = mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
});

const User = mongoose.model("User", schema);

//Routes GET, POST
app.post("/register", (req, res) => {
  const user = new User({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  });

  user.save((error) => {
    if (error) {
      res.status(500).send(error);
    } else {
      res.send("User registered successfully");
    }
  });
});

//lister
app.listen(3000, () => {
  console.log("Express app listening on port 3000");
});

almost done! and finally, If it works then don't touch it :D

Conclusion:

Thanks for reading. You can clone it from GitHub-

git clone "https://github.com/akmojahid/hello_world.git"