The Mongoose function effectively records accurate data, however when utilizing an async function to retrieve it, the outcome is

I am currently working on retrieving data from a database and passing it to a function. The main issue I'm facing is that even though the query results are visible when logged, they appear as undefined when trying to access them through the function. This could be due to my async function setup with mongoose not being configured properly. Another possibility is that my understanding of asynchronous programming is limited, as I'm relatively new to this concept.

async function returnBlogThumbnails(filter = "recent", callback){
    console.log("returning blogs")
    //For now simply filter by most recent
        if(filter === "recent"){
            Blog.find({}).sort('-date').exec((err,docs) => {
                return docs;
            });
        }
}

Here is the code snippet for the function that calls the above function:

app.get('/', (req, res)=> {
    console.log("go home");
    //Invoke the query to database and then use an async function to return results
    database.returnBlogThumbnails().then((blogs) => {
        console.log(blogs);
        //res.render('home', blogs);
    });
});

While the console log displays the desired output, the calling function always returns undefined. Any insights or suggestions would be greatly appreciated. Thank you!

Answer №1

The issue arises from defining the function with a callback and attempting to call it as a promise. To correct this, your function should be adjusted to utilize promises:

async function fetchBlogThumbnails(filter = "recent") {
    return new Promise((resolve, reject) => {     // creating a promise
        console.log("fetching blogs");
        // Filtering by most recent for now
        if (filter === "recent") {
            Blog.find({}).sort('-date').exec((err, docs) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(docs);
                }
            });
        }
    });
}

Subsequently, in your route, you can invoke it as follows:

app.get('/', (req, res) => {
    console.log("heading home");
    // Query the database then use async function to retrieve 
    database.fetchBlogThumbnails()
        .then((blogs) => {
            console.log(blogs);
            // perform actions with retrieved blogs
        })
        .catch((err) => {
            console.log(err);
            // handle any errors
        });
});

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

Steps for styling an AngularJS Popup:1. Determine the desired appearance for

I have some code that displays a popup when clicked, along with its automatically generated CSS. I want to be able to make changes to the CSS by adding IDs or classes to it. How can I assign IDs or classes to this element so that I can easily target them f ...

Can one validate a single route parameter on its own?

Imagine a scenario where the route is structured as follows: companies/{companyId}/departments/{departmentId}/employees How can we validate each of the resource ids (companyId, departmentId) separately? I attempted the following approach, but unfortunate ...

Guide to deploying a Next JS App with Mongoose for MongoDB connectivity on Vercel

I am experiencing issues when trying to deploy my Next.js app on Vercel with a MongoDB connection. I have added environment variables on the Vercel site where we deploy the Next.js app. Is there anything wrong in the following file? next.config.js module. ...

Bug with FullPage scrollOverflow sections when scrolling with iScroll's scrollTo() function

I've encountered an issue while using FullPage with scrollOverflow: true. I need to scroll to a specific position in a scrollable section. The problem arises from the fact that FullPage utilizes a modified version of the iScroll plugin for these overf ...

Oops! SAPUI5 is encountering an issue with reading property '0' of undefined

Is there a possibility of encountering multiple errors leading to this specific error message? https://i.stack.imgur.com/RpWhw.png Despite searching online, it appears that the error occurs in the JavaScript file when getelementbyid returns null. However ...

NGRX Store: Unable to modify the immutable property '18' of the object '[object Array]'

While attempting to set up an ngrx store, I encountered 7 errors. Error Messages: TypeError: Cannot assign to read only property '18' of object '[object Array]' | TypeError: Cannot assign to read only property 'incompleteFirstPass ...

Storing the order of jQuery UI Sortable in the WordPress Admin Panel

My goal is to customize the order of taxonomy terms for each individual post in Wordpress. I have created a metabox on the EDIT POST page that contains custom taxonomy terms and made them sortable using JQuery. Here is my setup on the Wordpress backend: ...

"Live Logging with MongoDB and MongoHQ: Stay Updated in Real-Time

Currently, I am establishing a connection to MongoDB using Mongoose within my Node.js application. Upon checking the console.log, I have observed the following message being logged: mongoose.connect(myURL) var db = mongoose.connection db.on('error&a ...

What are the steps for including and excluding components in Parallax JS?

When working with Parallax JS: I am trying to modify the components within the <li> tags of my menu, but I am unsure how to do so without restarting the plugin. I cannot seem to find the destroy command. Currently, I am using the JQuery version of ...

The AJAX response shows a value of "undefined"

My HTML page contains these codes, which display a list of employees from the database. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery-1.10.2.js"></script> ...

approach for extracting values from nested objects using specified key

There are objects in my possession that contain various nested objects: let obj = { nestedObject: { key: value } } or let obj2 = { nestedObject2: { nestedObject3: { key2: value2 } } } and so on. Retrieving the values from these objects i ...

Navigate to a different webpage while employing sweetalert2 and extracting data using the GET method

Is there a way to use sweetalert2 for redirecting to deleting.php with a specific ID parameter? How can I include this dynamic data in the code snippet below, which is used to display options for editing and purging data from an SQL database? echo' &l ...

Retrieve the unfinished user input from React's Material UI Autocomplete

I've implemented Material UI's Autocomplete input with react-hook-form as shown below: import React from "react"; import {Controller} from "react-hook-form"; import {Autocomplete} from "@mui/material"; export const ...

What is the best way to add HTML tags both before and after a specified keyword within a string using JavaScript?

Imagine I have a string similar to this, and my goal is to add html tags before and after a specific keyword within the string. let name = "George William"; let keyword = "geo"; Once the html tags have been appended, the desired result should look like ...

Displaying MySQL data on an HTML page with Node.js

Hello there, I recently started delving into Node.js for the first time. My current project involves fetching data from MySQL and displaying it on my HTML page. However, when I try to access my website at http://localhost:3000/index.html, I encounter an er ...

What is the best way to handle JSON data errors when a value is undefined?

I am currently working on a piece of code that displays JSON data in HTML. However, if a value is undefined, it doesn't display anything. How can I handle this error so that if a value is undefined, it will show "N/A" instead of breaking the code? ...

Make changes or generate based on the boolean condition

In my collection, there are objects that may or may not have a boolean variable called verified. If this variable exists and is false, I want to update it to true. If the variable doesn't exist, I want to create it as true. query := bson.D{{Key: &qu ...

Using Angular 6's httpClient to securely post data with credentials

I am currently working with a piece of code that is responsible for posting data in order to create a new data record. This code resides within a service: Take a look at the snippet below: import { Injectable } from '@angular/core'; import { H ...

Angular template fails to reflect changes after manipulating objects

There is an object defined as: $scope.allSessions = { set: {}, pending: [] }; Subsequently, a method is used to populate the set property with multiple objects like this: "2014-06-07-11-30": { blah blah } This results in a list of dates bei ...

Restrict form submission when minimum and maximum requirements are not met using JavaScript

I'm currently using JavaScript to show an error message when a user clicks on the form submit button and the entered number is not within the specified min and max range. The problem I am facing is that even when the submit button is clicked, the form ...