skip to Main Content

I’ve watched multiple tutorials on how to connect mongodb with node.js
I’ve created a free account on mongodb.com, set a user name and a password, created a database, added an IP address on 0.0.0.0/0

on vsCode I’ve installed all necessary packages

and here is my code

const express = require('express');
const mongoose = require('mongoose');

const app = express();
const uri = "mongodb+srv://user_db:[email protected]/myDataBase?retryWrites=true&w=majority";

async function connect(){
try{
    await mongoose.connect(uri)
    console.log("connected")
    } catch(error){
        console.log(error)
    }
}
connect();

app.listen(3000,()=>console.log("server started"));

The server start but I have no message from mongodb, no errors just nothing happened.
I’ve tried multiple times to rewrite the code, created multiple account from mongodb but always the same result, nothing happened.

2

Answers


  1. I don’t have much knowledge about it but maybe this will works because it works in mine case i think doing like this will work try one time

    const mongoose = require('mongoose');
    
    main().then(res=> console.log("db connected successfully...!!!"))
    main().catch(err => console.log(err));
    
    async function main() {
      await mongoose.connect('mongodb://0.0.0.0:27017/my_server');
    }
    
    Login or Signup to reply.
  2. const uri = "mongodb://<username>:<password>@localhost:27017"
    

    Basically your mongodb will be started in the localhost:27017 but if you have updated the hosting service from localhost to 0.0.0.0 then you should use the ip instead of localhost otherwise the above given uri will work fine.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search