MongoDB and JS code not processing the conditional statement

Here is the code snippet I am currently working with:

if (checkUserExists(serverID, userID) === null) {
    console.log("was null");
    addNewUserToDB(serverID, userID, username);
} 

I am aiming for it to run only if mongoDB cannot find a match for both Server and UID. To achieve this, I have implemented the following function:

function checkUserExists(serverID, userID) {
    mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true, useUnifiedTopology: true});

    playerModel.findOne({"serverID": serverID, "userID": userID }, (err, player) => {
        if (err) {
            console.log(err);
        } else {
            console.log(player);
            return player;
        }
    });
}

If a user is found, it will return the user object. If not, it will return null. However, the if statement never seems to trigger.

Answer №1

When running the code inside the checkUserExists method, it is executed asynchronously, causing checkUserExists to not return anything immediately. To ensure that the response from findOne is waited for before returning, utilize async/await.

Here is an example:

async function checkUserExists(serverID, userID) {
  mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true });
  var response;
  try {
    response = await playerModel.findOne({"serverID": serverID, "userID": userID});
    return response;
  } catch (e) {
    // Error handling
    response = { "title": "error in retrieving players", "desc": ""};
    return response;
  }
}

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

Guide to setting up parameterized routes in GatsbyJS

I am looking to implement a route in my Gatsby-generated website that uses a slug as a parameter. Specifically, I have a collection of projects located at the route /projects/<slug>. Typically, when using React Router, I would define a route like t ...

A blank page is appearing mysteriously, free of any errors

I have experience with ReactJs, but I am new to Redux. Currently, I am working on implementing an async action where I call an API and display the data received from it. Initially, when all the Redux components (actions, reducers, containers) were on a sin ...

Manipulation of pixels using Three.js software

Looking for guidance on creating a web application that can efficiently manipulate image pixels, specifically from a webcam source. I think using a custom shader in Three.JS could achieve this, but I'm unsure of the process. Can anyone provide assista ...

Is it permissible to access an iframe directly by its name?

I recently came across some JavaScript code that directly accesses an iframe by its name, without using getElementById() or any other method. Surprisingly, this code seems to be functioning properly in browsers like Chrome, Firefox, IE10, and Safari for Wi ...

Exploring the attributes of cycled values in Vue.js

Currently, I am iterating over a list as shown below: <li v-for="item in filteredParentItems" v-if="item.action === 'list'" v-on:click="getNextPath" v-bind:data-next-path="item.nextPath" v-bind:data-action="item.action ...

Working with Vue.js to call component methods when the page loads

My payment implementation utilizes vue-js and stripe. I found that the only way to incorporate Stripe with vue-js was through the use of script.onload. Now, I am trying to access some of my methods within the onload function. Specifically, I want to call ...

"What is the most efficient method to display or hide multiple divs using

Hey, I'm trying to figure out how to work with showing or hiding multiple div elements quickly. Do I really need to number each div like "open,close,show_text"? It seems a bit repetitive if I have to do it for each div 10 times. Open 1 Close 1 hell ...

Finding the exact dictionary in a list of dictionaries using $match

I am curious if there is a way to use $match in MongoDB to locate an exact dictionary within a list of dictionaries My documents have the following fields: { _id: ObjectId("6644d9860e3b38f3dd724241"), fields: { allowed_urls: [ { url: ...

I am currently familiarizing myself with backend routes and everything seems to be going smoothly for the first time around. However, upon attempting to revisit the site for

https://i.sstatic.net/ZOBl6.png https://i.sstatic.net/Xzhej.png Whenever I navigate from the home page to the contact page and then back to the home page, it displays an error message saying the site can't be reached. var http = require("http&q ...

Sharding setup for Mongodb database featuring several distinct indexes

Within my mongodb database, I have a "users" collection that will be sharded. In addition to the standard _id field, there are three other fields that require indexing and uniqueness: username, email, and account number. It's important to note that n ...

Using jQueryMobile within ASP.NET WebForms

Would implementing jQueryMobile in an ASP.Net Web Form application be the best choice? What advantages and disadvantages come with utilizing jQueryMobile or another Mobile JS library in ASP.NET web Forms? ...

Extract the URL contained within the <a> tag using the src attribute of an <img> tag automatically

At first glance, this question may seem odd, but I haven't discovered any other method to resolve the issue. Please bear with me as I explain my objective in detail! Currently, I am utilizing a lightbox to showcase an image that enlarges when clicked ...

Defeat the all-powerful !important tag and enable dialog customization for positioning

I am currently developing a browser extension and I am encountering an issue with using JQueryUI to display a modal dialog. The problem arises when certain websites, for example espn.com, also utilize JQueryUI but do not properly scope their own elements. ...

Deactivate Search Functionality for Users who are not Logged in on an Angular 2 Application

The login component and view are functioning as intended, preventing users from accessing AuthGuard protected routes if they're not logged in. However, I'm facing a challenge with the search bar displayed on the home login screen (actually presen ...

Angular - Strategies for Handling Observables within a Component

I am new to Angular and recently started learning how to manage state centrally using ngRx. However, I am facing a challenge as I have never used an Observable before. In my code, I have a cart that holds an array of objects. My goal is to iterate over the ...

Other options besides re-flowing and repainting

After doing some research on various platforms like Stack Overflow, I've come across information stating that re-paints and re-flows can be quite taxing on a browser's resources. I am interested in learning about alternative CSS/JS techniques to ...

Subcomponent not receiving property correctly passed

I am currently working on a website that fetches property-related data from SDFI, a Danish national data provider. After incorporating feedback and restructuring the props component based on your suggestions, I encountered an issue with passing accurate va ...

Leveraging HTML5's local storage functionality to save and manage a collection of list elements within `<ul>`

I need help with saving a to-do list in HTML so that it persists even after refreshing the browser. Can anyone assist me? html <!DOCTYPE html> <html> <head> <title>My To-Do List</title> <link rel="sty ...

Creating a seamless connection between a nodejs backend and a frontend interface

I'm facing an issue with my CRUD app developed using nodeJs. The app interacts with a mysql database to perform Create, Insert, Delete, and Read operations. Here's an example of a read operation: app.get('/run',(req,res) => { con ...

Difficulty updating data in MongoDB using Angular and Express API

Currently engaged with a comprehensive MEAN stack project. I am attempting to append data to the "notes" array within my MongoDB document with ID #1. Here is a snapshot of the MongoDB document: > db.contacts.find().pretty() { "_id" : ObjectId("5a294af ...