代码之家  ›  专栏  ›  技术社区  ›  vijay user2768407

未能在NoDEJS 8中创建MangoDB连接

  •  1
  • vijay user2768407  · 技术社区  · 7 年前

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

    共同的

    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,
    };
    

    用户.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:无法读取user.js中未定义的属性“collection”

    笔记 :我以前曾尝试过使用较低版本,但在使用新版本时遇到了问题。

    3 回复  |  直到 7 年前
        1
  •  2
  •   vijay user2768407    7 年前

    在实际发生initmongo之前加载了user.js。因此mongodb将保留getdb变量的未定义值。

    重构的最简单方法是将getdb从变量更改为函数,这样代码看起来就类似于:

    共同的

    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;
        },
    };
    

    用户.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
  •  1
  •   Arif Khan codemt    7 年前

    使用前需要初始化 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);
    })
    
        3
  •  0
  •   mbuechmann    7 年前

    你已经声明了 initMongo 作为异步函数。当你打电话 初始化 它只是返回一个承诺,程序流继续。那样的话 getDb 尚未初始化。你可以等到承诺兑现或出现错误:

    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.
    });
    
    推荐文章