0

I am trying to connect to a mongodb dataset on local from a nodejs application in a local machine that runs on windows, I have the following index.js:

const express = require('express');
const bodyParser= require('body-parser');
const mongoose = require('mongodb');
const MongoClient = require('mongodb').MongoClient;
const { render } = require("ejs");

const app = express();

app.use( express.static( "public" ) );
app.set('view engine', 'ejs');

// Make sure you place body-parser before your CRUD handlers!
app.use(bodyParser.urlencoded({ extended: true }))

MongoClient.connect("mongodb://localhost:27017/ecommerce", {
  useNewUrlParser:true,useUnifiedTopology:true
},(err)=>{
  if(err){
    console.log("connection failed")
    console.log(err)
  }else{
    console.log("sucessfully connected")
  }
})

app.listen(3000, function() {
    console.log('listening on 3000')
  });

When I run

node index.js

I get the following response:

listening on 3000
connection failed
MongoServerSelectionError: connect ECONNREFUSED ::1:27017
    at Timeout._onTimeout (C:\Users\...\node_modules\mongodb\lib\core\sdam\topology.js:438:30)
    at listOnTimeout (node:internal/timers:569:17)
    at process.processTimers (node:internal/timers:512:7) {
  reason: TopologyDescription {
    maxElectionId: null,
    servers: Map(1) { 'localhost:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    compatibilityError: null,
    logicalSessionTimeoutMinutes: null,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    commonWireVersion: null
  }
}

I verified if the mongodb service is running, and I found that it is running

enter image description here

In addition I can access the same database from MongoDB Compass using the localhost and the port 27017.

I have mongodb version 6.0.

tammuz
  • 407
  • 5
  • 14
  • 1
    _"connect ECONNREFUSED ::1:27017"_ Looks like `localhost` is translated to a IPv6 address on your machine. You can either enable IPv6 in your MongoDB server, or just use `"mongodb://127.0.0.1:27017/ecommerce"`. – rickhg12hs Mar 11 '23 at 03:12

1 Answers1

0

In line three, you have used mongodb instead of mongoose. Please correct it as follows:

const express = require('express');
const bodyParser= require('body-parser');
const mongoose = require('mongoose'); //fixed
const MongoClient = require('mongodb').MongoClient;
const { render } = require("ejs");

const app = express();

app.use( express.static( "public" ) );
app.set('view engine', 'ejs');

// Make sure you place body-parser before your CRUD handlers!
app.use(bodyParser.urlencoded({ extended: true }))

MongoClient.connect("mongodb://localhost:27017/ecommerce", {
  useNewUrlParser:true,useUnifiedTopology:true
},(err)=>{
  if(err){
    console.log("connection failed")
    console.log(err)
  }else{
    console.log("sucessfully connected")
  }
})

app.listen(3000, function() {
    console.log('listening on 3000')
  });