Executing a Javascript query on a database

Utilizing Express and Handlebars for a user-defined value stored in the database.

Handlebars is configured to present "{{userMotto}}" as the value. Express carries out the following:

function validateUser(req, res, next) {
    if (!req.user) {
        res.render('index', {
            user: req.user
        });
    } else {
        currentUser = req.user.username;
        userMottoCaught = fetchFromDatabase("motto", currentUser);
        next();
    }
}

The objective is to set "userMottoCaught" with the matching data from the database. The query used is:

function fetchFromDatabase(dbCollection, dbUID) {
    this.dbCollection = dbCollection;
    this.dbUID = dbUID;

    return MongoClient.connectAsync(hiddenkeys.mongodbUri)
        .then(function(db) {
            return db.collection(dbCollection).findOneAsync({
                _id: dbUID
            });
        })
        .then(function(item) {
            console.log("Found: ");
            console.log(item);
            return dbQueryResult;
        })
        .catch(function(err) {
            //error handling
        });
}

The challenge is extracting and returning the dbQueryResult back to the main function within queryDatabase. It seems stuck in a sub-function loop that prevents it from being returned properly. I've experimented with promises using Bluebird but remain unsure about the resolution. Callbacks have been considered too, yet seem complex to implement given my current code structure.

Upon rendering the page, the display method includes:

router.get('/', validateUser, function(req, res) {
    res.render('dashboard', {
        user: req.user,
        userMotto: userMottoCaught
    });
});

Presently, the output on the page reads: "Motto: [object Promise]", indicating a lapse in returning the correct value to the primary function.

Seeking guidance from anyone well-versed in these matters.

Cheers,

Dean

Answer №1

Perhaps implementing a callback is necessary in this scenario

function checkUserAuthentication(req, res, next) {
    if (!req.user) {
        res.render('index', {
            user: req.user
        });
    } else {
        currentUser = req.user.username;
        fetchUserMotto = fetchDataFromDatabase("motto", currentUser,function(err,data){
       fetchUserMotto = data
       next();
       });
    }
}

The queryDatabase function should have the following structure

function fetchDataFromDatabase(collectionName, userID, cb) {
    this.collectionName = collectionName;
    this.userID = userID;

    return MongoClient.connectAsync(hiddenkeys.mongodbUri)
        .then(function(db) {
            return db.collection(collectionName).findOneAsync({
                _id: userID
            });
        })
        .then(function(result) {
            console.log("Data found: ");
            console.log(result);
            databaseResult = JSON.stringify(result.motto);
            cb(null,databaseResult)
        })
        .catch(function(error) {
            // Handle error
            cb(error);
        });
}

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

Creating a dynamic multi-choice dropdown list with Django and Vue.js

I have been attempting to implement the Vue.js multiselect component from the following link: However, I am encountering an issue where instead of the expected multiselect dropdown, the output is not as desired and looks like this: https://i.sstatic.net/ ...

Learn how to iterate through child elements of an element's children in JavaScript

I am struggling to retrieve an element's children and then access the children of each child element. Even though I have attempted this code, I cannot figure out why it is not functioning correctly: var myElement = $('.a-container'); var my ...

Dealing with errors in Next.js api: Best practices

When it comes to organizing code in Next.js api handlers, what is the most effective practice? In a video I watched, the presenter suggested placing all REST routes in two specific files: pages/api/users/index.ts would manage operations that do not requ ...

AngularJS offers a single checkbox that allows users to select or

For my code, I need to implement a single checkbox. In my doc.ejs file: <tr ng-repeat="folder_l in folderlist | orderBy:created_date" > <td> <div class="permit"> <input class="chkbtn move_check" type="checkbox" id=" ...

Resolving DataTables Error

Here is my JavaScript code snippet. <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.2.1/css/but ...

Tips for improving the quality of your images

How can I adjust image quality/dpi without changing pixel size? I have an image with a specific pixel size that I need to reduce in quality before saving. If I want to decrease the quality to 87%, how do I achieve this using the following functions? func ...

State of cart is currently empty, local storage fails to reflect product quantity changes, utilizing redux as a potential solution

I am experiencing an issue with my state where the cart appears empty. When I add a new product, the state's cartItem[] is empty and does not display previous items. Similarly, state.cartItems is also an empty array when retrieved from useSelector(). ...

Is it possible to use a Jasmine spy on a fresh instance?

In need of assistance with testing a TypeScript method (eventually testing the actual JavaScript) that I'm having trouble with. The method is quite straightforward: private static myMethod(foo: IFoo): void { let anInterestingThing = new Interesti ...

Displaying a random item from the state in React.JS

After storing some items in the state, I want to have the ability to click a button and have a random item from that array displayed. The current issue is that it only works on the initial click, and then it continually displays the same item after the fir ...

Move items from one list to another using JavaScript

In my scenario, I have a userlist that is populated from a database. Below is the implementation of the Userlist: <select id="Userlist" name="cars" runat="server" multiple="true" style="width: 270px; height: 200px;"> </select> The objective i ...

Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor... My goal was simple - to create a line graph. Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output. In the ...

Tips for organizing HTML logic in a separate document

I am faced with the task of displaying a list in HTML based on specific conditions: <!-- Display list if there are more than 5 results --> <div list.numberOfResults > 10"> <b>Name: </b>{{list.name}} <b>ID ...

Sweetalert is currently experiencing issues with its service functionality

I've searched around but can't find a clear solution to my issue. I need help with implementing sweetalert function in my component, specifically for data deletion using the service. https://i.sstatic.net/o6W2n.png Component Swal({ title: ...

Angular app fails to process HTTP GET request

After successfully setting up the back-end for my app using the MEAN stack, everything seemed to be working well. I had implemented various HTTP handlers for POST, PATCH, and GET requests, with POSTs and PATCHes functioning smoothly - interacting seamlessl ...

Express Validator is unable to display error messages

Hi there, I'm looking to create a messaging system for my upload website. I am using express-validator along with connect-flash and express-messages. app.js const { check, validationResult } = require('express-validator'); . . . app.post( ...

Can someone assist with deciphering this code?

I have come across some code and I am unsure of what language it is written in. How can I convert it to HTML? You can find the code here: http://pastebin.com/ePPXkhMP I need to make some edits to this code, but I am not sure how to go about converting it ...

Issue with a input element having relative positioning within a flexbox

Objective: Aim to align the middle DIV (MIDDLE) within a flexbox row in the center. Issue: The right element includes an input element with relative positioning. Consequently, the middle DIV element (MIDDLE) is no longer centered but instead shifted to th ...

Every time I attempt to log into my app, I encounter a persistent 401 error message

I've implemented a user/login route that retrieves a user, compares their password with a hashed version, creates a token, and sends it to the front end. However, I encountered a persistent 401 error in the console on the front end, leading to the fin ...

Error encountered when executing a count query on MongoDB using the ReactiveMongo library

I am currently developing a Play 2.3.2 application that utilizes a MongoDB database. Within my application, I have two collections: recommendation.tags and recommendation.requests. These collections are structured in JSON format as follows: 1) recommendati ...

What is the best method for users to add a div element and its contents?

As someone new to the world of web development, I am currently learning and working on a project. I have encountered an issue with creating a custom div that includes a link and user-defined text. I want the div to be generated automatically when the use ...