skip to Main Content

This is the simple code of connecting the express js to mongodb, and i also install the both packages, so why i’m facing this error?

const express = require("express");
const app = express();

app.listen(3000,() => {
    console.log("Server is running at port number 3000");
})

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/myDatabase",{
    useNewUrlParser:true,
    useUnifiedTopology:true
})
.then(()=>{console.log("Connection is Succeed")})
.catch((e) => { console.error("Received an Error", e); });

Error I’m facing, they are not connecting.

Server is running at port number 3000
(node:25888) [MONGODB DRIVER] Warning: useNewUrlParser is a deprecated option: useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version       
(Use `node --trace-warnings ...` to show where the warning was created)
(node:25888) [MONGODB DRIVER] Warning: useUnifiedTopology is a deprecated option: useUnifiedTopology has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version 
Received an Error MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
    at _handleConnectionErrors (C:UsersASUSOneDriveDesktopweb devBackend DevelopmentExpress and MongoDB connectionsnode_modulesmongooselibconnection.js:809:11)
    at NativeConnection.openUri (C:UsersASUSOneDriveDesktopweb devBackend DevelopmentExpress and MongoDB connectionsnode_modulesmongooselibconnection.js:784:11) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}

2

Answers


  1. Instead of using ‘mongodb://localhost:27017/myDatabase’ try below code

    const express = require("express");
    const mongoose = require("mongoose");
    const app = express();
    
    app.listen(3000,() => {
        console.log("Server is running at port number 3000");
    })
    
    
    mongoose.connect("mongodb://127.0.0.1:27017/myDatabase",{
        useNewUrlParser:true,
        useUnifiedTopology:true
    })
    .then(()=>{console.log("Connection is Succeed")})
    .catch((e)=>{console.log("Received an Error")});
    
    Login or Signup to reply.
  2. I had the same problem. just replace the localhost to 127.0.0.1.
    So your code changes from this:

    
    mongoose.connect("mongodb://localhost:27017/myDatabase",{
        useNewUrlParser:true,
        useUnifiedTopology:true
    })
    

    to:

    
    mongoose.connect("mongodb://127.0.0.1:27017/myDatabase",{
        useNewUrlParser:true,
        useUnifiedTopology:true
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search