1

I'm trying to prepare a general function which will allow me to use any function on any database/collection. I'm not sure im doing this correctly. Here's my function code in node.js:

function use_db(db_url, func, ...args) {
    let prom;
    // noinspection JSIgnoredPromiseFromCall
    var lele = MongoClient.connect(db_url, (error, client) => {
        console.log('Connected');
        const db = client.db();

        console.log(db);

        prom = func(db, ...args);
        client.close();
        console.log('Disconnected successfully');
    });
    console.log(lele, 'whaat?');
    return prom;
}

I want it to return value prom but this happens:

  • first output is console.log(lele, 'whaat?'); which value is undefined 'whaat?'

  • then 'Connected'

  • and the last is 'Disconnected successfully'

So obviously prom is not defined at this moment

Why output is in this order? Why console.log(lele, 'whaat?'); runs first? Any ideas how can I improve this function, so it will use any other function to work on specific mognoDB database?

EDIT://

function connectDB(db_url) {
    return new Promise((res, rej) => {
        MongoClient.connect(db_url, (error, client) => {
            if (error) return rej(error);
            console.log('Connected');
            const db = client.db();
            return res({
                db,
                client
            });
        });
    });
}

async function use_db(db_url) {
    console.log('Start');
    const {
        db,
        client
    } = await connectDB(db_url);
    console.log('After db connection');

    return [db, client];
}

let temp_list = use_db(db_url);
const db = temp_list[0];
const client = temp_list[1];

let no_user = can_create_user(db, temp_email);

if(no_user) {
    //some code
}

How Can I leave active connection to the database and use db everytime for other functions? It doesn't wait for promise to resolve

2 Answers2

0

Node.js is asynchronous it does not wait for any blocker operation. check this

function connectDB(db_url) {
    return new Promise((res, rej) => {
        MongoClient.connect(db_url, (error, client) => {
            if (error) return rej(error);
            console.log('Connected');
            const db = client.db();
            return res({
                db,
                client
            });
        });
    });
}

async function use_db(db_url, func, ...args) {
    console.log('Start');
    try {
        const {
            db,
            client
        } = await connectDB(db_url);
        console.log('After db connection');
        const prom = func(db, ...args);
        client.close();
        console.log('Disconnected successfully');
        return prom;
    } catch (error) {
        console.log(error);
    }
}
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37
  • Thanks for help! I tried it, but it still doesn't seem to be working. I pasted the code above, in the edited question. – SecurityBreach Apr 06 '19 at 20:04
  • @JavaBoon are you getting any error. – Rahul Sharma Apr 06 '19 at 20:06
  • `(node:12624) DeprecationWarning: Cursor.each is deprecated. Use Cursor.forEach instead.` and `(node:12624) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.` Only those two – SecurityBreach Apr 06 '19 at 20:07
  • 1
    it's just a warning, not an error. what's `func` function is doing. check this it might help https://stackoverflow.com/questions/55537880/every-second-run-throws-mongoerror-topology-was-destroyed/55538144#55538144 – Rahul Sharma Apr 06 '19 at 20:08
  • In this case it's a reference to `can_create_user ` – SecurityBreach Apr 06 '19 at 20:11
  • Alright, I will try it out (the link) – SecurityBreach Apr 06 '19 at 20:12
  • I checked it out. I learned that the best way is to leave active connection to the database. I attempted to recreate connection everytime i used it. My progress is updated in editet question – SecurityBreach Apr 06 '19 at 20:36
0

Alright, I just worked around this and merged it all in few functions, where each connects to mongo and then disconnects after. I gave up. Here's a working example of adding a user to my database.

function add_user(db_url, name, surname, email, password) {
    MongoClient.connect(db_url, { useNewUrlParser: true }, (error, client) => {
        const db = client.db();

        db.collection('users').find({email: email}).toArray(function(err, result) {
            if(result.length === 0) {
                console.log('Adding new user');
                insert_into_users(db, name, surname, email, sha256(password));
            } else {
                console.log('E-mail already in database');
            }

            client.close();
        });
    });
}

function insert_into_users(db, name, surname, email, password) {
    db.collection('users').insertOne({
        name: name,
        surname: surname,
        email: email,
        password: password,
        liked_films: []
    });
    console.log('New user created');
}