MongoDB无法等待结果

时间:2018-09-21 09:36:20

标签: node.js mongodb express

我无法让MongoClient.connect等待结果,然后再继续。 我正在尝试从连接mongoclient的server.js传递db到我的post / api请求的route / api.js。但这不起作用,我总是得到:

  

TypeError:无法读取未定义的属性“ collection”

这是我的路线/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;

编辑:

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))

两个console.log()都是 undefined ......正常吗?

1 个答案:

答案 0 :(得分:1)

将此代码用于您的server.js。您的代码无法正常工作,因为在需要时未调用您的函数。

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;