Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const MongoClient = require('mongodb').MongoClient;
- let connectionInstance;
- // 链接用基础配置, 可以再封装传入, 也可做成多利.
- const url = "mongodb://localhost:27017";
- const dbName = "test";
- const user = "root";
- const password = "123456";
- const authSource = "admin";
- exports.getInstance = (next) => {
- if (connectionInstance) {
- next(connectionInstance);
- return;
- }
- MongoClient.connect(url, {
- auto_reconnect: true,
- useNewUrlParser: true,
- authSource,
- auth: {
- user,
- password,
- },
- }, (err, client) => {
- if (err) throw new Error(err);
- console.log("Connected successfully to server");
- const databaseConnection = client.db(dbName);
- connectionInstance = databaseConnection;
- connectionInstance.client = client;
- next(null, databaseConnection);
- });
- };
- exports.getInstanceAsync = () => {
- return new Promise((resolve, reject) => {
- if (connectionInstance) {
- resolve(connectionInstance);
- return;
- }
- MongoClient.connect(url, {
- auto_reconnect: true,
- useNewUrlParser: true,
- authSource,
- auth: {
- user,
- password,
- },
- }, (err, client) => {
- if (err) {
- reject(err);
- return;
- }
- console.log("Connected successfully to server");
- const databaseConnection = client.db(dbName);
- connectionInstance = databaseConnection;
- connectionInstance.client = client;
- resolve(databaseConnection);
- });
- });
- };
Add Comment
Please, Sign In to add comment