serverSelection.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*!
  2. * Module dependencies.
  3. */
  4. 'use strict';
  5. const MongooseError = require('./mongooseError');
  6. const allServersUnknown = require('../helpers/topology/allServersUnknown');
  7. const isAtlas = require('../helpers/topology/isAtlas');
  8. const isSSLError = require('../helpers/topology/isSSLError');
  9. /*!
  10. * ignore
  11. */
  12. const atlasMessage = 'Could not connect to any servers in your MongoDB Atlas cluster. ' +
  13. 'One common reason is that you\'re trying to access the database from ' +
  14. 'an IP that isn\'t whitelisted. Make sure your current IP address is on your Atlas ' +
  15. 'cluster\'s IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/';
  16. const sslMessage = 'Mongoose is connecting with SSL enabled, but the server is ' +
  17. 'not accepting SSL connections. Please ensure that the MongoDB server you are ' +
  18. 'connecting to is configured to accept SSL connections. Learn more: ' +
  19. 'https://mongoosejs.com/docs/tutorials/ssl.html';
  20. class MongooseServerSelectionError extends MongooseError {
  21. /**
  22. * MongooseServerSelectionError constructor
  23. *
  24. * @api private
  25. */
  26. assimilateError(err) {
  27. const reason = err.reason;
  28. // Special message for a case that is likely due to IP whitelisting issues.
  29. const isAtlasWhitelistError = isAtlas(reason) &&
  30. allServersUnknown(reason) &&
  31. err.message.indexOf('bad auth') === -1 &&
  32. err.message.indexOf('Authentication failed') === -1;
  33. if (isAtlasWhitelistError) {
  34. this.message = atlasMessage;
  35. } else if (isSSLError(reason)) {
  36. this.message = sslMessage;
  37. } else {
  38. this.message = err.message;
  39. }
  40. for (const key in err) {
  41. if (key !== 'name') {
  42. this[key] = err[key];
  43. }
  44. }
  45. return this;
  46. }
  47. }
  48. Object.defineProperty(MongooseServerSelectionError.prototype, 'name', {
  49. value: 'MongooseServerSelectionError'
  50. });
  51. module.exports = MongooseServerSelectionError;