这是我的database.js 文件:
const MongoClient = require('mongodb').MongoClient;
const db = function(){
return MongoClient.connect('mongodb://localhost:27017/users', (err, database) => {
if (err) return console.log(err);
return database;
});
}
module.exports = db;
我将它添加到我的 server.js 中,如下所示:
var db = require('./database');
但是当我想这样使用它时
db().collection('orders')
我收到 TypeError(无法读取未定义的属性“集合”)
编辑:抱歉,我在写这个问题时遇到了问题,当然我使用了db().collection
最佳答案
问题在于您的导出以及对 Node 回调行为的误解。
const MongoClient = require('mongodb').MongoClient;
const db = function(){
return MongoClient.connect('mongodb://localhost:27017/users', (err, database) => {
// this is inside a callback, you cannot use the database object outside this scope
if (err) return console.log(err);
return database; // this database object is what you should be exporting
});
}
module.exports = db; // You are exporting the wrong variable
解决此问题的一种方法是(可能不是最好的)导出我们在回调中收到的数据库对象。示例:
const MongoClient = require('mongodb').MongoClient;
let database = null;
MongoClient.connect('mongodb://localhost:27017/users', (err, db) => {
if (err) return console.log(err);
database = db;
});
module.exports = database;
现在您可以使用数据库,但需要进行空检查。
var db = require('./database');
if (db !== null) {
db.collection('orders').find({}, (err, docs) => {
if (err) return console.log(err);
console.log(docs);
});
}
但这可能会导致当您需要database.js文件时一次又一次地建立连接(我对此不确定)。更好的方法是:
const MongoClient = require('mongodb').MongoClient;
let database = null;
const connect = () => {
if (database !== null) return Promise.resolve(database);
return new Promise((resolve, reject) => {
MongoClient.connect('mongodb://localhost:27017/users', (err, db) => {
if (err) return reject(err);
database = db;
resolve(database);
});
});
};
module.exports = connect;
然后像这样使用它:
var dbConnect = require('./database');
dbConnect().then((db) => {
db.collection('orders').find({}, (err, docs) => {
if (err) return console.log(err);
console.log(docs);
});
}).catch((err) => {
console.error(err);
});
关于javascript - 我的数据库文件有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43006692/