Troubleshooting problems with connecting Express JS and MongoDB

I've written a simple code to connect express js to mongodb, and I've installed both packages. However, I'm encountering an error. Can someone help me troubleshoot this?

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

The error I'm facing is that they are not connecting properly.

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:\Users\ASUS\OneDrive\Desktop\web dev\Backend Development\Express and MongoDB connections\node_modules\mongoose\lib\connection.js:809:11)
    at NativeConnection.openUri (C:\Users\ASUS\OneDrive\Desktop\web dev\Backend Development\Express and MongoDB connections\node_modules\mongoose\lib\connection.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
}

Answer №1

I encountered a similar issue but found a solution. Simply switch out localhost with 127.0.0.1. So your modified code will look like this:


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

transformed to:


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

Answer №2

Give this code a shot instead of the usual 'mongodb://localhost:27017/myDatabase'

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

app.listen(3000,() => {
    console.log("The server is now up and running on port 3000");
})


mongoose.connect("mongodb://127.0.0.1:27017/myDatabase",{
    useNewUrlParser:true,
    useUnifiedTopology:true
})
.then(()=>{console.log("Connection successful")})
.catch((e)=>{console.log("An error occurred")});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving all selected checkboxes in AngularJS

I am a beginner in angular js and here is my template: <div class="inputField"> <h1>Categories</h1> <div> <label><input type="checkbox" id="all" ng-model="all" ng-change="checkAll();" ng-true-value="1">A ...

What issues can arise in JavaScript if the URL length is not zero when there is no match found?

Upon clicking the "Open Windows" button in Code A, I expected the two links to open in two tabs simultaneously in Chrome, which is exactly what happened. However, when I added a blank line in the textarea control in Code B, only the link http:// ...

What is the best way to bring in styles to a Next.js page?

I am facing an issue with my app where I have a folder called styles containing a file called Home.module.css. Every time I try to include the code in my pages/index.js, I encounter the same error message saying "404 page not found.." import styles from & ...

Ways to implement user-specific rate limiting?

In my application, there is a credit-based usage system in place. Unfortunately, the current structure allows users to make multiple requests within a short time frame, leading to a faulty system where they end up with negative credit values due to double ...

extract data from a JavaScript object

Currently facing an issue extracting a String name from the JSON object's name. It is necessary to parse this type of JSON response obtained from the server. var response = { hopaopGmailsjIpW: { GmailsjIpW_totalEmails_count: 133, GmailsjIpW ...

Appending a JSON object to an array does not result in the object being added to the

Can anyone help me with an issue I'm facing? I have a code snippet where I am trying to push a JSON Object into an array, but the array is not updating properly. It only shows the last pushed element. var myData = {}; var id = 0; $("a").on('cli ...

Learn how to effortlessly move a file into a drag-and-drop area on a web page with Playwright

I am currently working with a drag-zone input element to upload files, and I am seeking a way to replicate this action using Playwright and TypeScript. I have the requirement to upload a variety of file types including txt, json, png. https://i.stack.img ...

After defining the MongoClient.connect() outside of app.js, encountering an error that says "Trying to access property 'db' of undefined"

Previously, I had a functional, single-file application structured as follows: const express = require('express'); const app = express(); const http = require('http'); const server = http.createServer(app); const io = require('sock ...

Instructions on passing a PHP variable as a parameter to a JavaScript function when a button is clicked

In my implementation of codeigniter 3, I have a view page where the data from $row->poll_question is fetched from the database. The different values within this variable are displayed on the voting.php page. Next to this display, there is a button label ...

Retrieve and save only the outcome of a promise returned by an asynchronous function

I am currently working on an encryption function and have encountered an issue where the result is returned as an object called Promise with attributes like PromiseState and PromiseResult. I would like to simply extract the value from PromiseResult and s ...

Is there a way to address the sporadic behavior of rxjs combineLatest when used in conjunction with ReplaySubject

My current struggle lies within this particular example: const r1 = new ReplaySubject(2); const r2 = new ReplaySubject(2); r1.next('r1.1'); r1.next('r1.2'); r2.next('r2.1'); combineLatest([r1, r2]).subscribe(console.log); // ...

Challenge with Vite, React, and MSW Integration

Having some trouble setting up MSW in a React application. It's unusual for me to come across issues like this. I've configured an environment variable VITE_MOCK set to true when running the yarn start:mock command. This should enable API mocking ...

A guide on resetting a Nodemon server using code

At the beginning of server start, I have an array of JSON objects that are updated. But if I make changes to the JSON data using NodeJS FS instead of manually editing it, Nodemon does not restart. Is there a way to programmatically restart nodemon? ...

Calculating the total distance using GPS coordinates stored in MongoDB is a straightforward process

A GPS device is already installed in a vehicle and continuously sending values (Latitude and Longitude) to be stored in a MongoDB database. Now, the goal is to calculate the total distance traveled using these coordinates from the database. Here's th ...

When working with Vuejs Composition API, I noticed that the value of a Reference object seems to disappear when I

Here is the code snippet that I am working with: <template> {{posts}} </template> <script> import { computed, ref } from 'vue'; import getPosts from '../composables/getPosts.js' import {useRoute} from 'vue-router ...

Break up every word into its own separate <span>

I am currently facing an issue with displaying an array of strings in HTML using spans. These spans are wrapped inside a contenteditable div. The problem arises when a user tries to add new words, as the browser tends to add them to the nearest existing sp ...

Unable to display socket data in Angular js Table using ng-repeat

div(ng-controller="dashController") nav.navbar.navbar-expand-sm.navbar-dark.fixed-top .container img(src='../images/Dashboard.png', alt='logo', width='180px') ul.navbar-nav li.nav-item ...

Using underscore.js to connect an object with $rootscope: a step-by-step guide

I have a variable storing data var tooltipsJson = [{ "Language": "en-GB", "Section": "Sales&Marketing", "ItemName": "CalculationType", "Texts": "Having selected the account heading select the calculation ..." }, { "Language": " ...

Is there a way to utilize a value from one column within a Datatables constructor for another column's operation?

In my Typescript constructor, I am working on constructing a datatable with properties like 'orderable', 'data' and 'name'. One thing I'm trying to figure out is how to control the visibility of one column based on the va ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...