employing a variable within a function that is nested within another function

I'm encountering an issue where I am using a variable within a nested function. After assigning a value to it, I pass it to the parent function. However, when I call the function, nothing is displayed.

function checkUserExists(identifier) {
  let user = false;
  UsersModel.findOne({ email: identifier }, function (error, foundUser) {
    if (!error && foundUser) user = foundUser;
    else {
      console.log("error or user not found: " + error);
    }
  });

  return user;
}

Answer №1

The issue at hand arises due to the asynchronous nature of the findOne function, causing the user variable to consistently return as false. It is imperative to utilize either async await syntax or incorporate a callback function within the function itself.

Here is an example that utilizes async await:

async function fetchData(key) {
  const result = await UsersModel.findOne({ email: key });
  if (result.error)
    return false;
  
  return result.foundUser;
}

Below is an example that employs a callback function:

function getData(key, callback) {
  UsersModel.findOne({ email: key }, (error, user) => {
    if (!error) callback();
  });
}

Answer №2

Gratitude goes out to FloWy and VLAZ

Prior to this improvement,

function verifyUser(key) {
  let user = false;
  UsersModel.findOne({ email: key }, function (error, foundUser) {
    if (!error && foundUser) user = foundUser;
    else {
      console.log("error or not found: " + error);
    }
  });

  return user;
}

With the implementation of callback functions within a method,

function verifyUser(key, callback) {
  UsersModel.findOne({ email: key }, function (error, foundUser) {
    if (!error && foundUser) return callback(foundUser);
    else return callback(false);
  });
}

When making the call,

verifyUser(username, function (user) {
// user can be utilized here
});

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

The JSX component cannot be utilized as `ToastContainer`

Check out this Code: import axios from "axios"; import React, { useState, useEffect } from "react"; import { ToastContainer, toast } from "react-toastify"; import loaderIcon from "../../assets/images/loader.gif"; imp ...

What is the best method for removing node and then reinstalling it using nvm?

In my Mac, I have successfully installed Nodejs, but it was done using the usual method. However, in my new role, I've been asked to utilize NVM for Node installation. Can you guide me on the best approach to uninstall Node and then reinstall it with ...

What distinguishes between the methods of detecting falsy and truthy values?

While working with JavaScript / Typescript, I often find myself needing to verify if a length exists or if a value is true or false. So, the main query arises: are there any differences in performance or behavior when checking like this... const data = [ ...

Sequelize - utilizing the where clause with counting

I have three models that extend Sequelize.Model and I have generated migrations for them. The associations are set up as follows: Cat Cat.belongsToMany(Treat, { as: 'treats', through: 'CatTreat', foreignKey: 'cat_id', } ...

After using browserify, when attempting to call the function in the browser, an Uncaught ReferenceError occurs

I am currently in the process of creating a compact NPM package. Here is a basic prototype: function bar() { return 'bar'; } module.exports = bar; This package is meant to be compatible with web browsers as well. To achieve this, I have inst ...

Explore various date formats using the datepicker functionality

I'm dealing with the code below: <script type="text/javascript" language="javascript" src="~/Scripts/bootstrap-datepicker.min.js"></script> <script type="text/javascript" language="javascript" src="~/Scripts/locales/bootst ...

Exploring Vue.js: Navigating Through an Array of Images Nested Within Another Array

I am looking to showcase images stored in an array called "image" within another array named product. Essentially, if a product has an array of 3 images, I want to display all 3 images, and so on. Here is the code snippet: <template> <div c ...

retrieve JSON object from deferred response of AJAX request

After utilizing Ajax to send an item to a SharePoint list, I aim to incorporate the jsonObject received in response into a list of items. Located in AppController.js $scope.addListItem = function(listItem){ $.when(SharePointJSOMService.addListIte ...

React does not allow objects as child elements. Instead, render a collection of children by using an array

Encountering an error with this React class Error: Objects are not valid as a React child (found: object with keys {_id, name}). If you meant to render a collection of children, use an array instead. Is there anything amiss here? I am passing the movies ...

To enable the standard PayPal 'donate' button functionality, you can remove the submitHandler from jQuery Validate dynamically

I need to insert a PayPal donate button into the middle of an AngularJS donation form, specifically by nesting the PayPal generated form tags within the donation form tags. This donation form is utilizing an older version (1.12) of jQuery Validate, which ...

Choose the text that appears in the input or textbox field when tapping or clicking on it

Desperately Seeking a Clickable Textbox The Quest: In search of a cross-browser textbox/input field that can select its content on click or tap. An elusive challenge haunting developers for years. The Dilemma: Using a touch device triggers the tap e ...

Utilizing webpack 4's JSON tree-shaking functionality for keys that include the hyphen character

I need assistance with utilizing webpack 4's JSON tree-shaking feature as I am encountering a hurdle. Here is an example of some functional code: import { accessibility_16 } from '@collab-ui/icons/data/iconsData.json'; console.log("access ...

Adjust the hue of the X axis labels to display a variety of colors within Chart.js

Utilizing Chart.js for my bar chart. The X axis labels contain 4 lines, and I want to change the color of each line individually rather than having all values in one color. var barChartData = { labels: [["Injection", 10, 20], // Change the color here ...

Building a Sharepoint application with Angular 2 using the CLI and Webpack

Trying to deploy an Angular 2 CLI App to a SharePoint 2013 site has been quite challenging. The app works fine when embedded via a Content Editor Webpart, but the console throws an exception: zone.js:158 Uncaught Error: Sys.ParameterCountException: Parame ...

Error: Validation error occurred with document - reason unknown

Recently, I've been working on developing a basic CRUD application using MongoDB as my database. However, I keep encountering an error labeled MongoError: Document failed validation, and I am struggling to pinpoint the issue. The data appears to be s ...

Determine the number of occurrences of specific values within a group of objects based on a

I have the following dataset: const data2 = [ { App: "testa.com", Name: "TEST A", Category: "HR", Employees: 7 }, { App: "testd.com", Name: "TEST D", Category: "DevOps", Employee ...

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

Verify whether a variable is empty or not, within the sequence flows in Camunda Modeler

When working with a sequenceFlow in a process instance, I need to check a condition that may involve a variable that has not been defined yet. I want the flow to proceed even if the variable is not defined, rather than throwing an ActivitiException. I hav ...

Struggling to get the AJAX code functioning correctly

Embarking on my journey with AJAX, I decided to test a simple example from the Microsoft 70515 book. Surprisingly, the code doesn't seem to be functioning as expected and I'm at a loss trying to figure out why - everything appears to be in order. ...

Ways to prevent users from pushing multiple child data or adding more than one child to a specific child in the Firebase database

How can we limit users from pushing more than one piece of data to the Firebase database in terms of security rules? I have attempted this approach without success. { "rules": { ".read": false, ".write": false, "voters": { // En ...