Home > OS >  Function that return undefined in node.js. Inside the function I have mongoDB.connect
Function that return undefined in node.js. Inside the function I have mongoDB.connect

Time:12-30

I tried to make function for my project in the service. This service need to check is user exists in my database, but my function(this function is checking) inside the class return undefined.

This is my code:

const express = require("express");
const mongoDB = require('mongodb').MongoClient;
const url = "here I paste url to my databse(everything is good here)";

class CheckService {

    isUserExists(username) {
        mongoDB.connect(url, (error, connection) => {
            if (error) {
                console.log("Error", '\n', error);
                throw error;
            }

            const query = {name: username};

            const db = connection.db("users");

          const result =  db.collection("users").find(query).toArray(
                function findUser(error, result) {
                    if (error) {
                        throw error;
                    }
                    const arr = [];
                    if (result.value === arr.value) {
                        console.log(false);
                        connection.close();
                        return false;
                    } else {
                        console.log(true);
                        console.log(arr);
                        console.log(result);
                        connection.close();
                        return true;
                    }

                });

           console.log(result);


        });
    }

}

module.exports = new CheckService();

I expected good result, but function doesn't return, that I want, unfortunately.

Please help!

CodePudding user response:

2 things wrong here. Firstly the first comment is correct. You're only logging the result and not passing back to the caller. Secondly, a quick peek at the mongo docs shows that retrieval methods are promises. You need to make the function async and add awaits where needed.

Mongo: https://www.mongodb.com/docs/drivers/node/current/fundamentals/crud/read-operations/retrieve/

Promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

CodePudding user response:

There are two problems with your function

  1. it doesn't return anything
  2. toArray() is a promise, so your console.log probably just prints a promise.

Probably you're looking for something like this:

class CheckService {

    async isUserExists(username) {
        const connection = await mongoDB.connect(url);
        const query = {name: username};
        const db = connection.db("users");
        const result = await db.collection("users").find(query).toArray();
        connection.close();
        return result.length !== 0;
    }

}

You'd then invoke it with something like

await new CheckService().isUserExists(username);

Though, it's worth noting that you probably don't need toArray and instead could use findOne or even count() since all you care about is existence. I probably also wouldn't instantiate a new connection each time (but that's not super relevant)

  • Related