When invoking a callback function with parameters inside an async callback function in mongoose, it results in the value being 'undefined'

I've encountered an unusual issue while attempting to call a callback within another callback using mongoose in my MEAN Stack setup.

myFunction = function (cb) {
        var projection = {
        '_id': 0,
        'var1': 1,
        'var2': 1
    }

    var order = {
        'var1': 1
    }

    User.find({})
        .select(projection).sort(order)
        .exec(function(err, docs){
            if(err){
                console.log(err);
                cb(err,docs);
            } else {
                console.log(docs);
                cb(err,docs);
            }
        });
};

When trying to execute the lines with cb(err,docs), it raises a "ReferenceError: cb is not defined"


What's particularly strange is that I have functions with even more nested callbacks where "cb" works as expected.

myFunction = function(cb){
    model1.count({var1:'test'}, function (err, count) {
        if(count) {
            model2.findOne({dat1:'hoho'}, function (err, doc){
                if (err) {
                    console.error(err);
                    cb(err,doc);
                } else {
                    cb(err,doc);
                }
            });                 
        } else {
            cb({message: "No items found"}, null);
        }    
    })
}

The above code gets called as follows...

function initial(something){
    myFunction(function(err, doc) {
        if (err){
            console.log(err.message);
        } else {
            //handle doc
        }
    });
}

Answer №1

Oh no, it appears that the calling function failed to adhere to the guidelines.

The function was called with:

myFunc(json, function(err,doc){
    //do something
})

Incorrect number of parameters...

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

Tips for saving a picture within a mongodb record using python and pillow

Currently, I am working on a piece of code that generates a thumbnail image from a specified URL: r = requests.get(image_url, stream=True, headers=headers) size = 500, 500 img = Image.open(r.raw) thumb = ImageOps.fit(img, size, Image.ANTIALIAS) My goal i ...

Assigning a specific data type value to an element as it enters the top of the viewport

I have a unique color code stored for each section, and when a section reaches the top of the screen (specifically -180px for the header), I want to dynamically change the text color of the header element as you scroll through the sections. Despite no erro ...

Enhancing Angular input validators with updates

Working on a project with Angular 6, I have set up an input field using mat-input from the Angular Material framework and assigned it an id for FormGroup validation. However, when I initialize my TypeScript class and update the input value, the validator d ...

Can a string variable be passed as a file in a command line argument?

Running a command line child process to convert a local file to another format is something I need help with. Here's how it works: >myFileConversion localfile.txt convertedfile.bin This command will convert localfile.txt to the required format an ...

Substitute the text within a personalized tag with the provided content

Need help with a dynamic string <li>&emsp;Content Test 1</li>. Looking for regEx solution to replace tags so the final output is <ul><li>Content Test 1</li></ul> (Removing &emsp and adding <ul> while pr ...

Creating a JSON file using an object to send requests in Angular

In my Angular 7 project, I am trying to send a multipart request to the server that includes a file (document_example.pdf) and a json file containing a data object (data_object_example.json). The content of data_object_example.json is as follows: { " ...

Unable to resolve Uncaught TypeError: Null property reading not possible

Although I am hesitant to seek help here, solving this seemingly simple error has proved to be quite challenging. No matter what solution I attempt, the error persists. I am currently developing an application on Google Sheets that allows users to track t ...

Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code: import {plainToClass} from "class-transformer"; import UserDto from "../../auth/dto/user.dto"; class JsonConverter { ...

Methods to maintain the select2 dropdown event open while interacting with another select2 dropdown

I have a situation where I need to dynamically add a class to a div whenever a select2 dropdown is open. To achieve this functionality, I am utilizing the open and close events of select2. The current code successfully adds the class when opening a selec ...

Tips for restoring lost data from localStorage after leaving the browser where only one data remains

After deleting all bookmark data from localStorage and closing my website tab or Chrome, I am puzzled as to why there is still one remaining data entry when I revisit the site, which happens to be the most recently deleted data. This is the code snippet I ...

Error: The 'getters' property is undefined in @vue/test-utils and cannot be read

I've been utilizing @vue-test-utils for unit testing in VueJS. This is what my store setup looks like: export default { root: true, state: { batches: [] }, getters: { getBatches: state => { return state.batches } } } The componen ...

Incorporate a search feature that queries a MongoDB database in Node.js and Express, retrieving all objects that contain a specified user input value

I am looking to create a search feature that can query my MongoDB database and retrieve all objects that contain the name I am searching for, either fully or partially. For example: I have a collection of products, and I want to display every product that ...

Convert TypeScript-specific statements into standard JavaScript code

For my nextjs frontend, I want to integrate authentication using a keycloak server. I came across this helpful example on how to implement it. The only issue is that the example is in typescript and I need to adapt it for my javascript application. Being u ...

Change Scenery by Using Arrow Keys

I am trying to increase the speed of my background when the up and arrow keys are pressed. Despite my attempts, it is not working as expected. The variable this.speed controls the speed of the background. To achieve this, I implemented an if statement t ...

What is the best way to create an arrow connecting a parent div to multiple child divs?

I'm faced with a challenge involving a reusable React list component that supports nested children. My goal is to visually connect the parent div to its direct children using arrows, similar to the image linked below. View List Component Image Below ...

The Google Maps API allows all markers to be connected to a single infowindow

I've been grappling with this issue for some time now, but I just can't seem to find a solution! I'm retrieving data from a database in Laravel using Ajax and then attempting to display infowindows for each marker on Google Maps. The markers ...

jquery method to make entire navigation bar clickable

I have a single menu bar. I recently discovered an interesting way to make the entire menu bar area clickable using jQuery. Design code snippet: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="MenuControl.ascx.cs" Inherits="MenuControl"%> ...

Exploring ways to loop through a JSON array and embed it into an HTML element

After the ajax request, the data returned is structured as follows: Data = [ ["18/02/2019", "A"], ["19/03/2019", "B"], ["21/05/2019", "C"], ] The ajax request was successful and the data is stored in a variable named Data within a function. ...

Spin a collection of shapes with text while maintaining the text's center and horizontal alignment

It seems like just basic math to me. I'm utilizing Konva to dynamically create shapes, which are saved as a label. This label contains a text element and a rectangle. My goal is to ensure that the text inside the rectangle is always a) centered both ...

The Android webview is blocking the display of a frame due to its X-Frame-Options being set to 'DENY'

Encountering an issue while attempting to display a Google calendar in a webview, an error is displayed: [INFO:CONSOLE(0)] "Refused to display 'https://accounts.google.com/ServiceLogin?service=cl&passive=1209600&continue=https://www.google.co ...