【问题标题】:failing to create mongodb connection in nodejs 8无法在 nodejs 8 中创建 mongodb 连接
【发布时间】:2018-06-26 16:55:03
【问题描述】:

Nodejs:v8.11.3 - mongo:v3.6.3

以下教程http://mongodb.github.io/node-mongodb-native/3.0/tutorials/crud/

app.js

const mongoDB = require('./common_mongo.js')
mongoDB.initMongo()

common_mongo.js

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'onthemove';

let getDb;
const initMongo = async () => {
    const client = await MongoClient.connect(url);
    getDb = await client.db(dbName);
    await getDb.collection('comments').insert({text: 'hello'});
    //WORKS
};

module.exports = {
    initMongo,
    getDb,
};

user.js

const mongoDB = require('./common_mongo.js');

app.get('/users', async (req, res) => {     
    let list  = await mongoDB.getDb.collection('user').find({})
    //FAILS
    res.send(list);
})

TypeError: Cannot read property 'collection' of undefined in user.js

注意:我之前曾尝试过使用以前可以使用的较低版本,但是在新版本中我遇到了问题。

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    您在 initMongo 实际发生之前加载了 user.js。因此 mongoDB 将为 getDb 变量保存未定义的值。

    最简单的重构方法是将 getDb 从变量更改为函数,这样您的代码将类似于以下内容:

    common_mongo.js

    const MongoClient = require('mongodb').MongoClient;
    const url = 'mongodb://localhost:27017';
    const dbName = 'onthemove';
    
    let db;
    const initMongo = async () => {
        const client = await MongoClient.connect(url);
        db = await client.db(dbName);
        await db.collection('comments').insert({text: 'hello'});
    };
    
    module.exports = {
        initMongo,
        getDb() {
          return db;
        },
    };
    

    user.js

    const mongoDB = require('./common_mongo.js');    
    
    app.get('/users', async (req, res) => {     
        let list  = await mongoDB.getDb().collection('user').find({})
        res.send(list);
    })
    

    更进一步,您可以定义一个 getter 而不是 getDb

    module.exports = {
        initMongo,
        get db() {
          return db;
        },
    };
    
    app.get('/users', async (req, res) => {     
        let list  = await mongoDB.db.collection('user').find({})
        res.send(list);
    })
    

    【讨论】:

      【解决方案2】:

      使用getDb之前需要初始化,下面的代码可能对你有帮助

      const mongoDB = require('./common_mongo.js');
      
      app.get('/users', async (req, res) => {   
          if (!mongoDB.getDb) {  //Check getDb initialise or not
              await mongoDB.initMongo();
          }
          let list  = await mongoDB.getDb.collection('user').find({})
          //FAILS
          res.send(list);
      })
      

      【讨论】:

      • 由于 mongo 无法创建连接,因此它总是会返回未定义的。
      • 1: @arif 看看答案...特别是 getDb 函数 2:我想创建公共数据库连接,不想检查代码 3 中的每个请求:快乐编码..谢谢
      【解决方案3】:

      您已将initMongo 声明为异步函数。当您调用initMongo 时,它只会返回一个承诺,程序流程会继续。在这种情况下,getDb 尚未初始化。你可以等到 promise 完成或者发生错误:

      mongoDB.initMongo().then(function () {
          // connection succeeded. Do the stuff from user.js
      }).catch(function (err) {
           //failure callback. Doing the stuff from user.js won't make any sense here.
      });
      

      【讨论】:

        猜你喜欢
        • 2023-02-07
        • 2021-02-09
        • 1970-01-01
        • 2020-09-13
        • 2021-06-25
        • 2019-01-12
        • 1970-01-01
        • 2021-09-20
        • 1970-01-01
        相关资源
        最近更新 更多