简体   繁体   English

无法在nodejs 8中创建mongodb连接

[英]failing to create mongodb connection in nodejs 8

Nodejs : v8.11.3 - mongo : v3.6.3 Nodejs:v8.11.3 - mongo:v3.6.3

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

app.js app.js

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

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

Note : I have tried this earlier with lower versions it used to work ,but with there new versions im facing problem. 注意 :我之前尝试使用它曾经使用的较低版本,但是新版本即将面临问题。

You have user.js loaded prior to initMongo actually occurs. 在initMongo实际发生之前加载了user.js. So the mongoDB will hold undefined value for the getDb variable. 因此mongoDB将保留getDb变量的未定义值。

Simplest possible way to refactor this would be to just change getDb from variable to function so your code will look similar to this: 最简单的重构方法是将getDb从变量更改为函数,这样您的代码看起来就像这样:

common_mongo.js 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 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);
})

even further you can define a getter instead of the getDb 更进一步,你可以定义一个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);
})

You need to initialise before using getDb , following code may help you 您需要在使用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);
})

You have declared initMongo as an asynchronous function. 您已将initMongo声明为异步函数。 When you call initMongo it just returns a promise and the program flow continues. 当您调用initMongo它只返回一个promise并继续执行程序流程。 In that case getDb is not initialized yet. 在这种情况下, getDb尚未初始化。 You can wait until the promise is fulfilled or an error occurrs: 您可以等到承诺履行或发生错误:

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.
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM