pass boolean value from middleware to express route handler

In a middleware I have defined, my aim is to fetch and return a boolean value like this:

module.exports = {
   authenticatepracticename: function(pname) {  
       ecollection.find({ $and: [{'name':pname},{'status' : 'active'}] }).exec(function (err, result) {
           if (err) return false;
           if(result.length == 1){
               // console.log('true');
               return true;
            }
            else{
                // console.log('false');
                return false;
            }
       });  
   },
   // ... 
}

This value needs to be sent back to my express controller in the following way:

exports.checkcredentails = function (req, res) {  
    var result = practice.authenticatepracticename(practiceName);
}

The issue I'm facing is that while the middleware function is being invoked, the returned value is undefined.

Answer №1

If you are receiving an `undefined` result when calling `practice.authenticatepracticename`, it could be due to the asynchronous nature of the `ecollection.find` function. The `authenticatepracticename` function may be ending before returning any value, which in JavaScript would result in `undefined`.

To address this issue, consider implementing a callback function from your `checkcredentials` function to `authenticatepracticename` as shown below:

Example:

exports.checkcredentials = function (req, res) {  
    practice.authenticatepracticename(practiceName, function(err, result){
        // handle errors and results here, for example by sending them back to a customer
        res.send("Result: " + result);
    });
}

Below is an example implementation for the `authenticatepracticename` function:

authenticatepracticename: function(pname, cb) {
    ecollection.find({ $and: [{'name': pname}, {'status': 'active'}] }).exec(function (err, result) {
        if (err) return cb(err)
        if(result.length === 1){
            cb(null, true)
        } else {
            cb(null, false)
        }
    });  
}

I hope this provides some clarity on how to improve the situation.

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

Utilizing Angular.JS to sort items based on the chosen option in a select dropdown menu

I am utilizing the WP API to display a list of posts on a page from a JSON file. I have successfully implemented filtering through an input field named searchrecipe, which allows me to search for post titles. However, I am facing a challenge with filterin ...

Execute the validation directive using the digest cycle

This particular directive is designed to determine whether a given value exists within the associated datalist or not. It functions flawlessly when I input text into the field, but it fails to work properly if the datalist undergoes changes as a result o ...

When you try to refresh or manually enter a URL with React Router, the expected JSON data may be replaced with HTML data

Currently, I am developing a MERN website where I have implemented React-router for navigation. The links work fine when clicked, but the issue arises when I refresh the webpage or manually enter a URL. It seems that the React router URLs do not function p ...

Validating the body in Node.js for POST and PUT requests

When working in a production setting, what is considered the standard for POST / PUT body validation? I typically approach it like this: const isValid = (req.body.foo && /[a-z0-9]*/i.test(req.body.foo)) This method involves checking that the var ...

Node.js & Express: Bizarre file routes

It's quite strange how my local paths are functioning. Let me show you an example of my directory structure: public > css > bootstrap.css public > js > bootstrap.js templates > layout > page.ejs (default template for any page) tem ...

Unplanned pathways on a node-based server

Building a server, I've utilized the following code snippet: function uniqueString(length) { var result = ''; var characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; for (var i = length; i &g ...

Reasons why the Express Route fails to store cache while executed in a separate file

My code works fine when it's all in one file, but the caching stops working when I move it to a separate middleware file. Can someone help me understand why the caching isn't functioning properly in my middleware? Here is the working code: var e ...

AngularJS 1.7.8 causing compatibility issues with angular-ui-bootstrap 2.5.6

Currently delving into AngularJS, I am striving to transform a project that originally operated on regular Javascript, jQuery, and Bootstrap framework into an AngularJS single-page endeavor while still incorporating the Bootstrap library. Following the pro ...

Issue with Angular: $rootScope:infdig error encountered while trying to assign a directive attribute using a controller variable

One of the directives I implemented prevents certain values from being entered into an input field. For instance, if the user tries to enter 0, 10, or 17, a validation error will occur. Although this functionality is functioning correctly, I now need to d ...

I am facing difficulties in showing the data in my Ionic view when attempting to connect to my php API

Attempting to utilize a PHP API for data display is posing a challenge. The PHP side appears to be functioning correctly, as the data is being displayed through echo. However, encountering an error when trying to fetch the data in the Ionic view using http ...

Load image in browser for future display in case of server disconnection

Incorporating AngularJS with HTML5 Server-Side Events (SSE) has allowed me to continuously update the data displayed on a webpage. One challenge I've encountered is managing the icon that represents the connection state to the server. My approach inv ...

Display a JSON object on a web browser

I am trying to display a JSON object on a web browser using HTML. The object is already in a text file and has been properly formatted for readability. My goal is to maintain the same formatting when displaying it on the browser. ...

What are the steps to transform an object containing arrays into strings and then embed them into my HTML code?

Here is the code I need to add to my errors array and send the values to my HTML client-side template: { "email": [ "user with this email already exists." ] } I am looking for something like this: "user with t ...

To ridicule a service giver

I am currently working on a module where the configuration involves using a provider that I need to mock. The provider itself includes a register function which takes 2 arguments, and a $get function that returns an object. However, these details may not ...

Struggling with getting an angularjs directive to function properly (beginner in node.js and angularjs)

I am currently in the process of learning AngularJS and Node.js as I try to develop a small website named "hello website." However, I have encountered an issue with an AngularJS directive in my project structure: root + angularFiles ------ angularMen ...

Node.js is indicating that the certificate has expired

When using Mikeal's request library (https://github.com/mikeal/request) to send an https request to a server, I keep encountering an authorization error of CERT_HAS_EXPIRED. request({ url: 'https://www.domain.com/api/endpoint', ...

Unable to find the requested view using ejs and expressjs

Recently, I delved into exploring NodeJS and found it to be quite fascinating. However, I've encountered a perplexing issue in relation to view rendering. My goal is to implement the MVC pattern, hence I structured my project as follows: https://i.st ...

Tips for creating an effective update method in Prisma

I need help fixing my PUT method in Prisma to update all plan connections when updating my checkout this.connection.update({ where: { id }, data: { name, description, picture, updatedAt: new Date(), plans ...

Extracting Information from Cloud Firestore through an Express API

I have encountered an issue while trying to retrieve data from four different documents in my firestore database collection. The current code successfully fetches data for the first function, but all subsequent functions return the same data as the first ...

HtmlWebpackPlugin can cause issues with loading relative path files on websites that are not located in the root directory

I have set up webpack and the HtmlWebpackPlugin to automatically include bundled js and css files in an html template. new HtmlWebpackPlugin({ template: 'client/index.tpl.html', inject: 'body', filename: 'index.html' ...