title: How to handle mongoDB general operations in node.js
body: <p>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:</p>
  
  <pre><code>function use_db(db_url, func, ...args) {
      let prom;
      // noinspection JSIgnoredPromiseFromCall
      var lele = MongoClient.connect(db_url, (error, client) =&gt; {
          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;
  }
  </code></pre>
  
  <p>I want it to return value <code>prom</code> but this happens:</p>
  
  <ul>
  <li><p>first output is <code>console.log(lele, 'whaat?');</code> which value is <code>undefined 'whaat?'</code></p></li>
  <li><p>then <code>'Connected'</code> </p></li>
  <li><p>and the last is <code>'Disconnected successfully'</code></p></li>
  </ul>
  
  <p>So obviously <code>prom</code> is not defined at this moment </p>
  
  <p>Why output is in this order? Why <code>console.log(lele, 'whaat?');</code> runs first?
  Any ideas how can I improve this function, so it will use any other function to work on specific mognoDB database?</p>
  
  <p>EDIT://</p>
  
  <pre><code>function connectDB(db_url) {
      return new Promise((res, rej) =&gt; {
          MongoClient.connect(db_url, (error, client) =&gt; {
              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
  }
  </code></pre>
  
  <p>How Can I leave active connection to the database and use <code>db</code> everytime for other functions? It doesn't wait for promise to resolve</p>