DEV Community

Cover image for MongoDB connections using mongoose - 3
Mysterio
Mysterio

Posted on

MongoDB connections using mongoose - 3

Hello Guys today i am going to show you how to create mongoDB atlas connnection in Express.
I have already covered the folder structure of MERN and MongoDB setup in my previous 2 blogs so please check it out and then come back here.

  1. MERN CRUD -Setup - https://dev.to/shubhamtiwari909/mern-crud-setup-148a
  2. https://dev.to/shubhamtiwari909/2-mern-mongodb-setup-434g

Lets get started...

  • So, We have created a folder named Backend in our project and inside it we have created two file called mongo.js and Queries.js

  • Open the mongo.js in your VScode editor and write this code inside it.


const mongoose = require("mongoose");

const Database =
  "mongodb+srv://Your_UserName:Your_Password@cluster0.d9wx7.mongodb.net/Your_Database_Name?retryWrites=true&w=majority";

module.exports = async () => {
  await mongoose.connect(Database, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  }).then((res) => {
    console.log("connected successfully")
  }).catch((err) => {
    console.log("error")
  });;

  return mongoose
};

Enter fullscreen mode Exit fullscreen mode
  • Kindly fill Your username,password and database name in the Url
  • We are exporting the database connection using module.export and using async function for the connection method.
  • It will extablish a connection with mongo db atlas and will return a promise , if the connection is successfull, it will resolve the promise and make a connection and if the connection is failed , then it will reject the promise and gives an error
  • If you dont have mongoose installed please check my blog " MERN CRUD - setup" , i have given detailed explaination there.

Creating the Schema -

  • Remember in our Backend folder, we have created a folder name "Schema" and inside the "Schema" folder we have file named "Schema.js", open that file and write this code there .
const mongoose = require('mongoose');

const userSchema = mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    number: {
        type: String,
        required: true
    }
})

module.exports = mongoose.model('users',userSchema)
Enter fullscreen mode Exit fullscreen mode
  • We have created our schema with 3 fields name, email and number along with some attributes like datatype which these going to store and required true property which means the field is a required field and cannot be left empty.
  • Then we have created our model using "mongoose.model('user',userSchema)", Here 'user' is the collection name which will hold all the data , its like a table in MySQL.
  • Then we have exported this model using module.export and will import it in our Queries.js file with mongodb connection

  • Now open Queries.js and import the connection from mongo.js file and Schema from Schema.js file

const mongo = require("./mongo");
const userSchema = require("./Schema/Schema");
.
.
.
rest of the code
Enter fullscreen mode Exit fullscreen mode
  • Here we have imported the connection method of mongo and our Schema from Schema.js file and is ready to use these to perform our CRUD operation in MERN.

Thats it for this post, i will continue this series in the next blog where i will be discussing some modules which we are going to use in our Backend code
THANK YOU FOR READING THIS POST AND IF YOU FIND ANY MISTAKE OR WANTS TO GIVE ANY SUGGESTION , PLEASE MENTION IT IN THE COMMENT SECTION.
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/react-hooks-usecontext-1ml2

https://dev.to/shubhamtiwari909/redux-combinereducers-mk0

https://dev.to/shubhamtiwari909/introduction-to-tailwind-best-css-framework-1gdj

Discussion (0)