Executing the collection.find() function triggers an internal server issue and eventually leads to a timeout error

My ExpressJS backend was running smoothly with hardcoded data, but when I integrated MongoDB into the system, my requests for data started timing out. I added a record to a collection using the command prompt:

> db
stackmailer

> db.sites.find()
{ 
    "_id" : ObjectId("55ef5c1a7f6857848b7149b7"), 
    "title" : "Stack Overflow", 
    "icon" : "http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png" 
}

The MongoDB server is hosted at localhost:27017

2015-09-08T23:58:51.394+0200 I CONTROL  [initandlisten] MongoDB starting : pid=6836 port=27017 dbpath=C:\data\db\ 64-bit host=JEROEN-LAPTOP
2015-09-08T23:58:51.422+0200 I NETWORK  [initandlisten] waiting for connections on port 27017
2015-09-08T23:58:54.760+0200 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51658 #1 (1 connection now open)

To read the data, I have this code:

var db = require('mongoskin').db('localhost:27017/stackmailer');
router.get('/', function (req, res, next) {
    db.collection('sites').find().toArray(function (err, result) {
        if (err) {
            console.log(err);
            throw err;
        }
        console.log("found sites!");
        console.log(result);
        res.send(result);
    });
}

And in AngularJS, it's called like this:

StackExchangeService.getSites().then(function(data) {
    $scope.data.sites = data;
});

angular.module('StackMailer.Services', [])
    .factory('StackExchangeService', function($q, $http) {
    var service = {
        getSites: function() {
            return getData('/sites');
        }
    };

    function getData(url)
    {
        var d = $q.defer();
        $http.get(url, ({ timeout: 10000 }))
        .then(function(response, status) {
            console.log("successfully retrieved data");
            d.resolve(response.data);
        }, function(response, status) {
            console.log("couldn't retrieve data " + status);
            d.reject(response);
        });
        return d.promise;
    };

    return service;
});

However, after the specified timeout, I see "couldn't retrieve data 0" in the console. The console.log calls inside router.get() don't display any output.

I suspect there might be an issue with the MongoDB connection, even though everything seems to be set up correctly.

When examining the ExpressJS output, I notice the following for 3 requests:

GET / 304 5.335 ms - -
GET /css/stackmailer.css 304 4.784 ms - -
GET /js/stackmailer.js 304 1.250 ms - -
GET /sites 500 479.902 ms - 1424
GET /tags 304 2.303 ms - -
GET /css/stackmailer.css 304 0.937 ms - -
GET / 304 1.028 ms - -
GET /css/stackmailer.css 304 1.231 ms - -
GET /js/stackmailer.js 304 1.608 ms - -
GET /tags 304 1.156 ms - -
GET /sites - - ms - -
GET / 304 2.988 ms - -
GET /css/stackmailer.css 304 4.508 ms - -
GET /js/stackmailer.js 304 2.022 ms - -
GET /tags 304 1.336 ms - -
GET /sites - - ms - -

The first request to /sites returns HTTP 500 and then times out. This error message appears in the console log:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Interestingly, when I wrap the db.collection() call in a try-catch block and attempt to log the error, the HTTP 500 error disappears, but no output is shown either.

Any thoughts on what could be causing this issue?

Answer №1

It seems like you might not be seeing any error logs due to potential configuration settings in your application that haven't been mentioned here.

If an error were to occur, it should look something like this:

Error: URL must be in the format mongodb://user:pass@host:port/dbname

This error occurs when the connection string is not formatted correctly for the driver. The correct format should resemble this:

var db = require('mongoskin').db('mongodb://localhost:27017/stackmailer');

Note that including 'mongodb://' is essential, while other details like port number (if using the default) may be omitted.

Additionally, I noticed that you have this setup in your "route" module and potentially throughout your application wherever a database connection is needed. It is recommended to establish the database connection only once per application and share it across instances where necessary.

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

Troubleshooting a Safari bug with element.click()

When the 'subButton2' button is clicked, the 'uploadBtn'(display:none;) should also be clicked. This functionality needs to work across different browsers: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_html_click The cod ...

Where did my HTML5 Canvas Text disappear to?

I am encountering a common issue with my code and could use some guidance. Despite numerous attempts, I can't seem to figure out why it isn't functioning properly. To better illustrate the problem, here is a link to the troublesome code snippet o ...

Is it possible to create an index.html page with all the necessary head tags to prevent duplicate code across multiple html pages?

Imagine I am using app.js or a Bootstrap CDN link for all of my HTML pages, but I don't want to include it in every single page individually. Is there a way to create an index.html file that includes this so that all other HTML pages load the head fro ...

Testing Equality in Unit Tests: Comparing Objects and Arrays

Forgive me for this seemingly silly question, but I'm having trouble understanding it. I am a newcomer to both testing and JavaScript, so please bear with me. Here is the test in question: describe('initialized from copy job functionality&apos ...

Using a curly brace in a React variable declaration

After completing a react tutorial, I started customizing the code to suit my requirements. One specific section of the code involved a component that received a parameter called label. render() { const { label } = this.props; ... } For instance, I re ...

What is the process for uploading files from NextJS directly from the browser to either Cloud Storage or an FTP server?

Is there a way to upload files from the browser using NextJS directly to Cloud Storage or an FTP server? I'm looking to upload files directly from the browser to a storage server. Do you think I can utilize node-ftp in the API routes of Nextjs, like ...

When the window size is reduced, the navigation vanishes

Whenever I resize the window, the navigation bar disappears. Here is the image of the page before resizing the window https://i.sstatic.net/UiRB9.png Below is the image after resizing the window https://i.sstatic.net/X00d2.png Displayed below is the cod ...

Execute Node.js code and view the output in a web browser

I recently started working with nodejs. I successfully installed node (expressjs) and npm on my server via SSH. In my app.js file, I included the following code: var express = require('express'); var app = express(); app.get('/ ...

When I click the button, it deletes the DOM element and hides it, preventing me from

I'm facing a simple issue that I can't quite wrap my head around. Whenever I input a value into the form and click the button to run the function, the 'loading' element disappears and doesn't reappear. Here is the JavaScript code ...

Design for implementing "new" functionality in JavaScript

I recently delved into the world of JavaScript Patterns through Stoyan Stefanov's book. One pattern that caught my attention involves enforcing the use of the new operator for constructor functions, demonstrated with the following code snippet: funct ...

Adonis 5 and Vue encountering the error message 'E_ROUTE_NOT_FOUND'

I am currently working on a project using Adonis v5 as the backend and Vue 2 as the frontend. I have encountered an issue where, after building the Vue frontend into the public Adonis folder, accessing a specific route directly in the browser results in an ...

Unable to set values to an array of objects in JavaScript

Currently, I am facing an issue in my node.js project where I am unable to assign values to an array of objects. This problem has occurred before, but I just can't seem to figure out the root cause. My suspicion is that it might be related to variable ...

The $ionicPopup is not being recognized by the $scope

I am facing an issue with creating a dynamic popup where images change opacity when clicked. It currently works fine outside of a function, but I need to implement it within a function. Below is my controller code: $scope.imgIds = ['0', ...

The show more/show less link for a long jQuery paragraph is malfunctioning

I encountered an issue while coding where the "read more" link works correctly, but the "show less" link does not. Despite my efforts, I cannot seem to identify the error. Within this code snippet, there is an anchor tag with class="show-less" that I am u ...

Javascript functions fail to execute as intended

I have a project called calc, which includes various functions such as init. Within this project, there are three buttons that I am adding to the div using jquery. When a user clicks on any of these buttons, it should trigger the inputs function. Based on ...

Start up a server using Angular along with Node.js and Express framework

I am encountering an issue with configuring Express as a server in my Angular application. The app loads without any issues when accessing the HOME route, but when trying to access another route, I receive an error message: Cannot GET / This is how I hav ...

Ways to implement a single AJAX function for multiple buttons

I need to call the same AJAX function for multiple buttons. Please assist with the code provided below. This particular code will create buttons and upon clicking on them, it displays details... please assist with resolving this issue. The code generated ...

What is the best approach to transforming my jQuery function into CSS to ensure responsiveness?

I have created a jQuery animation with four functions named ani1(), ani2(), ani3(), and ani4(). Everything is working fine on desktop, but now I am facing the challenge of making it responsive for mobile devices. I am looking for CSS code to replicate the ...

Unknown identifier in the onClick function

I want to create a JavaScript function that can show or hide a paragraph when clicking on an arrow. The challenge I'm facing is that I have a list of titles generated in a loop on the server, and each title is accompanied by an arrow. Initially, the c ...

Accept JSON data in ASP.NET MVC action method for posting data

I have a model class named Parcel which contains the parameters Name and CenterPoint: public class Parcel { public string Name { get; set; } public object CenterPoint { get; set; } } The values for these parameters are obtained from a map. When a ...