【发布时间】: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