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);
})
类型错误:无法读取 user.js 中未定义的属性“集合”
注意:我之前曾尝试过使用它曾经工作的较低版本,但对于新版本我遇到了问题。
最佳答案
您在 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);
})
关于javascript - 无法在 nodejs 8 中创建 mongodb 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51038194/