Why is the ExpressJS response for a POST request returning as undefined upon connecting to MongoDB?

I am currently working on a web application using the MEAN framework and following the MVC design pattern. My goal is to execute a POST request from the Angular front-end to search for a document in my server-side MongoDB (version 2.4.9). The console logs indicate that the query is successful, but I encounter an issue when trying to send the response back to the client as the query result turns out to be undefined.

While I understand that NodeJS operates asynchronously and utilizes callbacks, I'm facing difficulty in pinpointing the error within my code. Despite attempting to implement returns and callbacks, I have been unable to resolve the issue. I'm unsure of how to leverage the controller to access the model and ultimately transmit the response.

Below is my code snippet responsible for connecting to the database (model):

module.exports = {

readDocument : function(callback, coll, owner) {  

    // Establish connection to the database
    MongoClient.connect("mongodb://localhost:27017/tradingpost", function(err, db) {
            if (err) { 
            console.log("Cannot connect to db (db.js)");
            callback(err);
            }
        else {
                console.log("Connected to DB from db.js: ", db.databaseName);

                //Retrieve document by owner

                // Obtain documents collection
                var collection = db.collection(coll);

                // Locate document
                collection.find({owner: owner}).toArray(function (err, result) {
                    if (err) {
                        console.log(err);
                    } else if (result.length) {
                        console.log('Found:', result);
                    } else {
                        console.log('No document(s) found with specified "find" criteria!');
                    }

                // Close connection
                db.close();

                return callback(result);
                });

        }
    })
}}

Additionally, here is the controller responsible for sending the response:

var model = require('../models/db');
exports.sendRecentPosts = function (req,res) {

   // Connect to the DB
   // Execute query for recent posts
   // Close the connection
   // Transmit the data to the client
   var result = model.readDocument(dbCallback, "gs", "Mana");
   res.end( result );

};

Example of the client's post request:

    // Employ post method for secure queries
    // Request recent posts for display purposes
    $http.post('/recent').
       success(function(responseData) {
             $scope.testValue = responseData;
           }).
       error(function(responseData) {
             console.log('Recent posts POST error. Received: ', responseData);
         });

Snippet showcasing my express route:

var goodsServices = require('../controllers/gs-server-controller.js');
app.post('/recent', goodsServices.sendRecentPosts);

This has been a challenging issue for me, and despite conducting extensive research on the forum, no viable solutions have surfaced. Any feedback or suggestions would be greatly appreciated. Thank you.

Answer №1

It's surprising to see this question still unanswered. From my experience, I discovered that the results of all database queries are only returned once the transaction is finished. You might want to consider putting db.close() inside the success callback response of the find() function.

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

Perform an action when a key is held down and when it is released

I am looking to implement a function that needs to be called under certain conditions: It should be triggered every second while a key is being held down (for example, if the key is held down for five seconds, it should fire 5 times every second). If ...

Creating an API that manages multiple arrays and allows for easy updating

I'm currently diving into the world of noSQL and facing a challenge in structuring my model to efficiently handle hourly updates of leagues and matches from an api. The scores may change and new matches could be added, so I need a model that can accom ...

I can't figure out why my JavaScript recursion function isn't correctly counting the number of lines, words, and characters in a text

Seeking assistance with my JavaScript recursion program that is not functioning as expected. The goal is to extract words from a text file and output the count of words, lines, and characters. I am uncertain where my mistake lies, so any guidance on code m ...

Issue an api call when the value retrieved from mongoDB is empty

I am currently working on a project where I am utilizing the MEAN stack. My data is stored in MongoDB and I need to make API calls only if a certain value is null. While I have been able to retrieve the data from the database and call the API successfully, ...

Is it possible for .getElementByClassName to identify Ajax.GET elements?

I've run into a problem that I need help with: The issue arises when I have an API that makes an Ajax GET request. In the success function, it creates a button, a div, and several span elements with information inside, each with its own class. The GE ...

Encapsulate the HTTP request within a common function for reus

My rest-provider service handles all of my http calls, but I've noticed that each function is repeating a lot of the same http code. It seems like I should create a shared function to avoid this repetition and make it easier to update in the future. ...

A step-by-step guide on utilizing img src to navigate and upload images

I would like to hide the input type='file' element with id "imgInp" that accepts image files from users. Instead, I want them to use an img tag to select images when they click on a specific img tag. How can this be achieved using jQuery? Here i ...

Observing the closing of a modal window from a different controller in AngularJS

Within my main controller, I have a function called $scope.showDialog: $scope.showDialog = function(ev) { $mdDialog.show({ controller: 'DialogController', templateUrl: 'partials/dialog.tmpl.ejs', targetEvent: ev ...

Get the audio file to start downloading by clicking an HTML anchor link, without relying on the browser's

In my current project, I have an anchor link that directs to an MP3 file. My goal is to allow users to download this file by either right-clicking and selecting "Save Target As..." or by simply clicking on the link. However, I have encountered a problem w ...

How can I display a Material-UI Drawer that is nested within a Grid component?

I'm currently working on a web application using Material-UI. The main page is structured into 3 grids, all with a fixed height of 500px. I have a requirement to include a drawer within the middle grid that contains some action options. However, my cu ...

Unable to refresh JSON data in Datatables

Ensuring this operation is simple, I am following the documentation. An ajax call returns a dataset in JSON format. The table is cleared successfully, but even though data is returned according to the console statement, the table remains empty after the su ...

Running queries in a loop is not functional within node-firebird

When running multiple select queries in a loop, I encountered an issue that puzzled me. For simplicity, let's take a look at the code snippet below: var Firebird = require('node-firebird'); Firebird.attach({database: 'TEST'}, (e ...

Javascript is failing to fetch the desired text

I'm in the process of tweaking the code found at 'http://jsfiddle.net/vivin/RjqUf/' to allow users to select a line or word from a PDF. I've added the following JavaScript snippet at the end of the existing code: $(".textLayer").mouseu ...

During the compilation process of next.js, the middleware is being unnecessarily triggered multiple times

I am currently utilizing next.js in conjunction with express.js. Whenever I include a middleware (server.use(req, res, next)), it ends up being triggered multiple times during the page compilation process, leading to a complete app crash... const express ...

Tips for checking the validity of PHP variable names, such as $as['abc'], within an HTML textbox

Can anyone assist me with validating a user input PHP variable name such as $as_cap['abc'] during insertion? I need to verify if the format of the variable name is correct or incorrect. Currently, I am using eregi("^[a-z0-9_.'-]{1,50}$") ...

The Node Server using Express encountered a 404 Not Found error while trying to handle the app

I have set up the following route on my server: app.get('/coolPath', function (req, res) {} Oddly enough, this route works fine when I run it locally. However, once I upload it to the server, I encounter a 404 File or directory not found error. ...

How to extract information from a JavaScript object array in Node.js?

Currently, I am attempting to extract data from a JavaScript Object array by providing field names and then storing the data in an array. However, my current approach seems to be yielding incorrect results. Whenever I try to log the values stored in ' ...

Having trouble with Next.js and React Apollo Client not sending cookies?

Utilizing Apollo Client in my Next.js application as a GraphQL client, here is the function I use to create the client: let client: ApolloClient<any>; export const __ssrMode__: boolean = typeof window === "undefined"; export const uri: str ...

Experiencing difficulties when attempting to show or hide elements using jQuery

I spent several hours trying to figure this out and couldn't get it right. Is it feasible to create a jQuery script that will perform the following action when a <span> element is clicked: Check if any of the <p> elements are current ...

The Spring Data MongoDB push operation is failing to update multiple fields

I am working with a collection of data objects stored in MongoDB as follows: [ { "status" : "passed", "version" : "124" , "value" : 6 }, { "status" : "passed", "version" : "123" , "value" : 10 }, { "status" : "failed", "version" : "123" , "val ...