我已经初始化了与 mongodb 的连接,现在将 db 导出到其他 nodejs 文件。我该怎么做?
我想到了这样的事情,但它给出了错误。
let database;
export const connectDB = async () => {
const client = new MongoClient(config.dbUri, {
useUnifiedTopology: true,
});
try {
await client.connect();
database = client.db('azkaben');
logger.info('Connected to Database');
} catch (e) {
logger.error(e);
} finally {
await client.close();
}
};
export default database
错误:未定义的数据库值
database
导入时将始终为空。
connectDB
执行 aync 调用时,您的数据库变量已加载为空值。
connectDB
你可以database
从这里回来。
export const connectDB = async () => {
const client = new MongoClient(config.dbUri, {
useUnifiedTopology: true,
});
try {
await client.connect();
database = client.db('azkaben');
return database; // you can get from here
logger.info('Connected to Database');
} catch (e) {
logger.error(e);
} finally {
await client.close();
}
};
export const connectDB = async () => {
if (database) return database; // return if database already connected.
const client = new MongoClient(config.dbUri, {
useUnifiedTopology: true,
});
try {
await client.connect();
database = client.db('azkaben');
return database; // you can get from here
logger.info('Connected to Database');
} catch (e) {
logger.error(e);
} finally {
await client.close();
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句