Promise chain failure in express

I've developed an express.js server for managing REST API requests and extracting data from a MongoDB database. However, I'm encountering an issue with the promise chain when I send a GET request to a specific endpoint ("localhost:8081/api/getUserData"), and I'm struggling to comprehend the error message.

Here's the error that pops up: "[TypeError: Cannot read property 'db' of undefined]"

var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();
var rp = require("request-promise");
var cors = require('cors');

// Implement CORS before defining any routes
app.use(cors({ origin: '*' }));

/********************** REST API FUNCTIONS **********************/
app.get('/api/getUserData', function (req, res, next) {
  var context = {};
  console.log("in api getUserData")
  context.db_url = 'mongodb://localhost:27017/test';
  establishDatabaseConnection(context)
    .then(retrieveAllUserLocations)
    .then(closeDatabaseConnection)
    .then(function (context) {
      res.send(context.userLocations)
    })
    .catch(function (error) {
      console.log("ERROR :");
      console.log(error);
    })
})
/********************** END REST API FUNCTIONS **********************/

function retrieveAllUserLocations(context) {
  context.db.collection("test").find().toArray().then(function (err, result) {
    console.log("Received from db: " + result.length + " objects");
    context.userLocations = result;
    return context;
  });
}

function establishDatabaseConnection(context) {
  console.log("Opening DB connection...");
  return MongoClient.connect(context.db_url)
    .then(function (db) {
      console.log("DB connection opened.");
      context.db = db;
      return context;
    })
}

function closeDatabaseConnection(context) {
  console.log("Closing DB connection");
  return context.db.close()
    .then(function () {
      console.log("DB connection closed");
      return context;
    })
}

/********************** STARTING SERVER **********************/
var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("Githex server listening at http://%s:%s", host, port)
})

I would greatly appreciate any assistance, particularly with an explanation as to where I may have gone wrong.

Thank you!

Answer №1

As mentioned by @adeneo in the initial comment, the missing db property is causing an issue in your code. Take a closer look at the first function:

app.get('/api/getUserData', function (req, res, next) {
  var context = {};
  console.log("in api getUserData")
  context.db_url = 'mongodb://localhost:27017/test';
  openDatabaseConnection(context)
    .then(getAllUserLocations)
    .then(closeDatabaseConnection)
    .then(function (context) {
      res.send(context.userLocations)
    })
    .catch(function (error) {
      console.log("ERROR :");
      console.log(error);
    })
});

Let's break down the code within this function:

  1. You initialize context as an empty object
  2. You assigned a db_url property to the object, which currently looks like

    context = {db_url: "mongodb://localhost:27017/test}
    
  3. You pass the context object into the openDatabaseConnection function
  4. Within the openDatabaseConnection function, you return a context object. However, this returned object is not being utilized. You need to invoke the getuserlocation() function with this returned value.

Instead of just using

.then(getAllUserConnection)

I suggest

.then(function(context){getAllUserConnection(context);})

This will effectively utilize the returned value and ensure it is properly utilized.

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

Is the error message from mongoose different than a MongoError instance?

My goal is to handle the E11000 duplicate key error, by intentionally inserting the same user with a matching UID. const MongoError = require('mongodb-core').MongoError async function insertUser(uid) { try { await userModel.create({ ...

Find the value of a JavaScript string variable using an alternative name

My latest JavaScript function is designed to fetch JSON data from either a server or local files on any browser. This piece of code processes JSON from two sources: an XMLHttpRequest response, or a variable imported via script. In the case of the latter, ...

Is there a way to set a default CSS background image using JavaScript in case the specified

When working with regular CSS, I can easily set a fallback image using this code in case the primary image is not available: .container { background-image: url(pics/img.webp), url(pics/img.png); } But when it comes to setting styles in JavaScript (such ...

The 'length' cannot be searched using the 'in' operator

I am experiencing an issue that I can't quite solve. I have come across solutions for this problem, but they all involve methods that don't use AJAX to retrieve data. If anyone can assist me with this, I would greatly appreciate it. Here is the J ...

Issues have been encountered with the ExpressJS post route as it is currently not functioning properly and

I'm currently working on a Mean stack application and have set up an expressjs backend post route to save data on the server. However, I'm encountering an issue where I receive an error message stating 'An error occurred in form api' fo ...

Can you please provide guidance on implementing automatic horizontal scrolling with pauses between each div?

setInterval(function scroll() { $(".box_auto").each(function(i, e) { $("html, body").animate({ scrollTop: $(e).offset().top }, 500).delay(500); }); setTimeout(function() { $('html, body').animate({ scrollTop: 0 } ...

Tips for determining what elements are being updated in terms of style

I need assistance with modifying the functionality of a webpage's dropdown menu. Currently, it displays when the mouse hovers over it, but I want to change it to appear on click using my own JavaScript. Despite setting the onmouseout and onmouseover e ...

Prevent Mui popover from closing when clicking outside

Currently, I have implemented Mui Popover with ReactJS from the link here. One issue I am facing is that when a user clicks outside the popover, it automatically closes. Is there a way to disable this default behavior? Additionally, I would like to add a ...

What seems to be the issue with loading this particular file into my JavaScript code?

When attempting to import a file into my code, I encountered an issue where the folder could not be found. Interestingly, when manually typing out the folder name, it is recognized and suggested by the system. Even providing the full path did not yield dif ...

Retrieve the duplicated items from an array by comparing two specific properties in JavaScript

I need assistance in identifying and retrieving duplicate objects within an array that share similarities in 2 specific properties. Consider the object structure below: let arry = [ {Level: "A-1", Status: "approved"}, {Level: &q ...

Why is the Google Map missing from the Bootstrap modal dialog?

I have multiple links on my website, each describing a different location with unique map data. I would like to display a modal bootstrap dialog with an embedded Google map when a user clicks on any of the links - ensuring that the location shown correspon ...

Retrieving every single .json file present in a specific folder

I'm working on developing an Android app that utilizes JSON data. Is there a method to establish a directory structure similar to this: http://......./jsons/*.json Or is there another way to append additional data into a JSON file (such as a.json) a ...

The error message "Declaration file for module 'mime' not found" was issued when trying to pnpm firebase app

Currently, I am in the process of transitioning from yarn to pnpm within my turborepo monorepo setup. However, I have run into an issue while executing lint or build commands: ../../node_modules/.pnpm/@<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

What is the best way to showcase the outcome on the current page?

This is a sample HTML code for a registration form: <html> <head></head> <body> <form id="myform" action="formdata.php" method="post"> username:<input type="text" name="username" id="name"><br> password:&l ...

Karma jasmine and an angular controller that utilizes the 'Controller as' syntax (where 'this' is used instead of $scope)

I'm having trouble setting up karma for my unit tests, specifically on a basic example: Here is the controller file: angular.module('balrogApp.requests', [ /* Dependencies */ ]) // Routes configuration .config(['$routeProvider&a ...

What is the best approach for presenting MySQL data on an HTML div through Node.js?

When working with Node.js, I prefer using Express as my framework. Here is the AJAX code I have on my member.ejs page: function load_member(){ $.ajax({ url: '/load_member', success: function(r){ console.lo ...

Passing dynamic modifiers in custom Vue.js directives

<Button ... v-tooltip.bottom="{ value: tooltip, disabled: !tooltip }" /> Is there a way to dynamically change the position of the tooltip from "bottom" to another modifier such as top, left, or right in PrimeVue? I have various modifi ...

jQuery sends ajax success to input type number

I am encountering an issue with the ajax success loading function when using input type number. Interestingly, when I switch the input type to text, it works perfectly fine. However, once I change the input type back to number, the loading ceases. <s ...

Tips for avoiding redundant AJAX requests

Currently, I am working with JavaScript and not jQuery. Imagine a scenario where I have 3 users in my database [Kim, Ted, Box] and 3 buttons structured as follows: <button class="user">Kim</button> <button class="user">Ted</button> ...

How can I create a static navigation bar and sidebar using Bootstrap 4?

Currently, I am utilizing HTML, Javascript, Bootstrap, and CSS to develop a fixed navbar and sidebar for our system. My objective is to ensure that the navbar and sidebar remain fixed even when users scroll down the page, while also maintaining responsiven ...