Jerlam
Jerlam

Reputation: 1101

MongoDB unable to wait result

I cannot make MongoClient.connect to await for the results before going on. I am trying to pass db from the server.js, where I connect my mongoclient, to my routes/api.js where I do my post requests. But it does not work, I always get:

TypeError: Cannot read property 'collection' of undefined

Here is my routes/api.js:

var db = require("../server");

router.post('/video_url', async (req, res) => {
    const cursor = db.collection('movie').findOne({ link: req.body.videoURL }, function (findErr, result) {
        if (findErr) throw findErr;
    console.log(cursor)
});

server.js:

var db = async function () {
    return await MongoClient.connect(MONGODB_URI, function(err, client) {
        try {
            if(err) throw err;

            db = client.db('sub-project');

            // Start the application after the database connection is ready
            app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));
            return db;
        }
        catch(ex) {
            console.log(ex)
        }
    });
}

module.exports = db;

EDIT:

var dbObject = (async function() {
    var connection = await new Promise(function(resolve, reject) {
        MongoClient.connect(MONGODB_URI, { useNewUrlParser: true }, function(err, client) {
            try {
                if (err) throw err;

                db = client.db('sub-project');

                // Start the application after the database connection is ready
                app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));
                resolve(db);
            } catch (ex) {
                console.log(ex)
                reject(ex);
            }
        });
    });
    return connection;
})();

    console.log("TYPEOF DB IN", typeof(dbObject))
    console.log("TYPEOF DB.COLLECTION IN", typeof(dbObject.collection))

The both console.log() are undefined... is that normal?

Upvotes: 0

Views: 189

Answers (1)

Dhaval Chaudhary
Dhaval Chaudhary

Reputation: 5835

Use this code for your server.js. Your code was not working because your function was not getting called when you are requiring it.

var dbObject;
(function() {
  MongoClient.connect(MONGODB_URI, { useNewUrlParser: true }, function(err, client) {
   try {
    if (err) throw err;

    db = client.db('sub-project');
    // Start the application after the database connection is ready
    app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));
   dbObject = db;
   } catch (ex) {
     console.log(ex);
   }
  });
 })();


 setTimeout(function() {
  console.log("TYPEOF DB IN", typeof(dbObject))
   console.log("TYPEOF DB.COLLECTION IN", typeof(dbObject.collection))
 }, 2000);

module.exports = dbObject;

Upvotes: 1

Related Questions