Guest User

Untitled

a guest
Sep 27th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. const MongoClient = require('mongodb').MongoClient;
  2.  
  3. let connectionInstance;
  4.  
  5. // 链接用基础配置, 可以再封装传入, 也可做成多利.
  6. const url = "mongodb://localhost:27017";
  7. const dbName = "test";
  8. const user = "root";
  9. const password = "123456";
  10. const authSource = "admin";
  11.  
  12. exports.getInstance = (next) => {
  13. if (connectionInstance) {
  14. next(connectionInstance);
  15. return;
  16. }
  17.  
  18. MongoClient.connect(url, {
  19. auto_reconnect: true,
  20. useNewUrlParser: true,
  21. authSource,
  22. auth: {
  23. user,
  24. password,
  25. },
  26. }, (err, client) => {
  27. if (err) throw new Error(err);
  28.  
  29. console.log("Connected successfully to server");
  30.  
  31. const databaseConnection = client.db(dbName);
  32. connectionInstance = databaseConnection;
  33. connectionInstance.client = client;
  34.  
  35. next(null, databaseConnection);
  36. });
  37.  
  38. };
  39.  
  40. exports.getInstanceAsync = () => {
  41. return new Promise((resolve, reject) => {
  42. if (connectionInstance) {
  43. resolve(connectionInstance);
  44. return;
  45. }
  46.  
  47. MongoClient.connect(url, {
  48. auto_reconnect: true,
  49. useNewUrlParser: true,
  50. authSource,
  51. auth: {
  52. user,
  53. password,
  54. },
  55. }, (err, client) => {
  56. if (err) {
  57. reject(err);
  58. return;
  59. }
  60.  
  61. console.log("Connected successfully to server");
  62.  
  63. const databaseConnection = client.db(dbName);
  64. connectionInstance = databaseConnection;
  65. connectionInstance.client = client;
  66.  
  67. resolve(databaseConnection);
  68. });
  69. });
  70. };
Add Comment
Please, Sign In to add comment