Unable to establish a connection with the Mongo Database

Apologies if this issue seems like a beginner one (I'm new to this platform)...

I've been attempting to configure my application to connect to the database, but I keep encountering an error and I can't pinpoint the problem.

Here's the code snippet:

    const express = require('express');
    const app = express();
    const ejs = require('ejs');
    const path = require('path');
    const mongo = require('mongodb').MongoClient;
    const dbUrl = 'mongodb://localhost:3000/contractformapp';
    const bodyParser = require('body-parser');
    const ObjectId = require('mongodb').ObjectId;

    mongo.connect(dbUrl, function(err, contract) {
        if (err) {
            console.log("Error connecting to the database");
        } else {
            console.log("Connection to the database was successful");
            contracts = contract.db('contractformapp').collection('contracts');
        }
    });

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));


    app.get('/', function (req, res) {
        contracts.find({}).toArray(function (err, docs) {
            if (err) {
                console.log(err);
                return;
            }
            res.render('index', { docs: docs });
        });
    });


app.listen(3000, 'localhost', (err) => {
    if (err) {
        console.log('err');
    } else {
        console.log('Server started listening');
    }
});


app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

When I try to execute nodemon and visit http://localhost:3000/

Server started listening
Error connecting to the database
ReferenceError: contracts is not defined

Answer №1

It is recommended to have your mongo server and express server running on different ports for optimal performance. Typically, the default port for mongodb is 27017.

Ensure that in your code, the database connection URL is set correctly like so: const dbUrl = 'mongodb://localhost:27017/contractformapp';

Additionally, make sure that your mongodb instance is active and running smoothly.

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

What is the best way to determine if an AJAX response is of the JavaScript content type?

There are multiple forms in my system, each returning different types of data. I need to be able to distinguish between a simple string (to display in the error/status area) and JavaScript code that needs to be executed. Currently, this is how I'm ha ...

Library for Typescript in Microsoft MakeCode Minecraft

Just started my journey in the world of Minecraft and I am currently trying to navigate through using javascript within the game. Specifically, I have some questions pertaining to javascript objects as I delve into the Windows 10 version of Minecraft. I am ...

Working with Hidden File Inputs in Python Selenium

Currently utilizing selenium-python with chromedriver. On a website, specifically , I am attempting to utilize send_keys() to upload a file to a file input field. The issue arises when the input element is only visible in the inspector once a file has be ...

javascript jquery chosen not functioning properly

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JavaScript</title> </head> <body> <h1 id="hey">List King</h1> <div class="Select-DB"> <select id="DB" class="chosen ...

Why is there a dot displaying in my countdown when the hours are zero? Also, why does my minute not show as 00 when it passes 59?

There is an issue with the minutes here. https://i.sstatic.net/M8pYB.png Also, there seems to be a problem with the hour dot: https://i.sstatic.net/55SFU.png const [time, setTime] = useState(60 * 60) const hour = time / 3600 let minutes = Math.floor(time ...

Starting a checkbox group with values based on total number

I am facing a challenge with a group of checkboxes that have values assigned as 1,2,4,8,16,32,64. Each number corresponds to a day of the week (e.g. Sunday, Monday etc...) The total value of the checkbox group is calculated as the sum of the selected chec ...

Using Rails: The Art of Safely Managing JavaScript code when working with AJAX on the client-side

How can I securely send a collection via to_json directly from the controller action to the client-side? When the request is sent from the controller action straight to the client-side without pre-processing, the process looks like this: An AJAX requ ...

Menu remains open on resizing browser, refusing to close

Welcome to my code snippet: HTML: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8> <title>Responsive Menu</title> <!-- CSS and JS link tags go here --> </body> </html> CSS: ...

What steps can I take to stop the window/body from scrolling "through" a modal div?

Let me simplify my layout for you: <body> [... lots of content ...] <div id="modal-overlay"> </div> </body> The body has so much content that the whole page scrolls. The styling for #modal-overlay looks like this: #m ...

Developing a quiz using jQuery to load and save quiz options

code: http://jsfiddle.net/HB8h9/7/ <div id="tab-2" class="tab-content"> <label for="tfq" title="Enter a true or false question"> Add a Multiple Choice Question </label> <br /> <textarea name ...

Unexpected alteration of property value when using methods like Array.from() or insertAdjacentElement

I'm encountering an issue where a property of my class undergoes an unintended transformation. import { Draggable, DragTarget } from '../Models/eventlisteners'; import { HeroValues } from '../Models/responseModels'; import { Uti ...

Utilizing Angular to Bind Data Visualization Charts Locally

I am attempting to use the Kendo UI Angular directives to bind a DataViz pie chart locally, but I am encountering an error that says: TypeError: Cannot call method 'toLowerCase' of undefined at h (http://localhost:51717/Scripts/kendo/kendo.d ...

Stop automatic image sliding by hovering in jQuery

How can I make the image slider pause on hover? Here is the code that I have been using: $(".col-md-8").hover(function() { clearTimeout(timer); }); It seems like this should work, but for some reason it's not. Can anyone ...

Unable to receive URL parameters using JavaScript on a mobile device

I have been developing a program that displays all users' buttons on a screen, except for the current user's buttons. I came across this code snippet to extract URL parameters: function getParameterByName(name, url) { if (!url) url = window.lo ...

Discover how to obtain an access token using Yelp API V3 with JavaScript

Currently in the process of learning how to utilize this system, however there appears to be an issue with my code. $.ajax({ dataType: "POST", url: "https://api.yelp.com/oauth2/token", grant_type: "client_credentials", client_i ...

Guide on parsing JSON object data and separating strings into individual variables

I have a metadata object with the following structure: "metadata": { "item0": "[id: 123][name: hello world][size: large][quanity: 2][price: $1.00]" "item1": "[id: 456][name: test 123][size: small][quanit ...

Tips for programmatically choosing images from a Google Photos collection?

Currently, I am attempting to use code in the console to automatically choose a photo from a Google Photos Album while browsing. I've tried this method so far: const photo = document.getElementsByClassName('p137Zd')[0].parentElement photo. ...

Exploring Variations in Color with React-three-fiber

When using both meshBasicMaterial and meshStandardMaterial in a React Three Fiber component to render a box with an image texture, the texture appears different from the original image. Despite trying to set colorManagement={false} in the canvas component, ...

Class does not have the capability to deserialize an array

I encountered this issue with my code (see image): https://i.sstatic.net/QxI0f.png Here is the snippet of my code: function CheckLoginData() { var user = []; user.Email = $("#tbEmail").val(); user.Password = $("#tbPassword").val(); $.ajax({ type ...

Use checkboxes to switch specific divs on and off based on their two assigned classes

Hey, I'm trying to implement some code with a specific structure: Initially, a main div is opened and checkboxes are created using a foreach loop. A checkbox is generated for each 'model' in an array. <div id='coltext'> & ...