Setup database MongoDB – Step 5

Setup database MongoDB – Step 5

Step 5: – Setup database MongoDB

  1. Mongodb.com
    • Login
    • Create cluster
    • Database access
    • Network access
  2. Package Commands to install
    • npm i mongoose
  3. MongoDB Compass download install
    • Connect with compass

mongodb+srv://shairy:shairy@123@demo.d8fem.mongodb.net/testMongoDB Connect with application

4. Go to Config .env file and paste

MONGO_URI = mongodb+srv://shairy:shairy@123 @demo.d8fem.mongodb.net /portfolio?retryWrites=true&w=majority

5. Create a new file db.js under config

const mongoose = require('mongoose');

const connectDB=async()=>
{
    const conn= await mongoose.connect(process.env.MONGO_URI,{
        useNewUrlParser:true,
        useCreateIndex:true,
        useFindAndModify:false,
        useUnifiedTopology: true 
    });
    console.log(`MongoDB Connected: ${conn.connection.host}`);
};
module.exports = connectDB;

6. Handle unhandled promise Rejection and check mongodb connected or not

const server=app.listen(
    port,
    console.log(`server running in ${process.env.NODE_ENV} mode using port  ${port}`));

process.on('unhandledRejection',(err,promise)=>{
    console.log(`Error: ${err.message}`);
    server.close(()=>process.exit(1));
})

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*