【问题标题】:MongoDB unable to wait resultMongoDB 无法等待结果
【发布时间】:2019-02-25 16:33:57
【问题描述】:

我不能让 MongoClient.connect 在继续之前等待结果。 我正在尝试将 db 从连接我的 mongoclient 的 server.js 传递到我执行发布请求的 routes/api.js。但它不起作用,我总是得到:

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

这是我的路线/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() 都是未定义...这正常吗?

【问题讨论】:

  • 我建议使用 mongoosejs.com 。这样您就不必担心连接问题。
  • 其实我是想先尝试纯mongoDB,理解一下再去mongoose,但不得不承认可能会放弃……mongoDB用起来太麻烦了。你会推荐我和尚吗?
  • 即使是纯 mongoclient 版本也很好用,让我为您提供一个很好的例子。这里有一些很好的答案stackoverflow.com/questions/47370487/…
  • 我已经看过这篇文章,但很遗憾我仍然无法解决我的问题:/
  • 你已经定义了 db 函数但是你没有调用它。你可以在 server.js 中有自调用函数,它可能会起作用。

标签: node.js mongodb express


【解决方案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;

【讨论】:

  • 它不工作仍然是同样的错误:db.collection 不是一个函数。但它可能来自 routes/api.js:我只调用 "var db = require("../server");"
  • 在此更改之后您是否重新启动了服务器?
  • 我正在使用 nodemon。
  • 但是,就像我的 routes/api.js 文件没有等待服务器返回 db 对象...
  • 即使它不等待。您的应用不会处理任何请求,因为您的应用仅在 mongo 连接后启动。
猜你喜欢
  • 2019-04-02
  • 2018-08-28
  • 2018-06-28
  • 2014-06-30
  • 1970-01-01
  • 1970-01-01
  • 2017-10-30
  • 2017-04-26
  • 1970-01-01
相关资源
最近更新 更多