Home > Enterprise >  MongoDb is not connected and I have no error
MongoDb is not connected and I have no error

Time:10-04

I've wached 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 adress 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 happend. I've tried multiple times to rewrite the code, created multiple account from mongodb but always the same result, nothing happend.

CodePudding user response:

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');
}

CodePudding user response:

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.

  • Related