Mongoose.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const mongoose = require('mongoose')
  2. const Settings = require('@overleaf/settings')
  3. const Metrics = require('@overleaf/metrics')
  4. const logger = require('@overleaf/logger')
  5. const { addConnectionDrainer } = require('./GracefulShutdown')
  6. if (
  7. typeof global.beforeEach === 'function' &&
  8. process.argv.join(' ').match(/unit/)
  9. ) {
  10. throw new Error(
  11. 'It looks like unit tests are running, but you are connecting to Mongo. Missing a stub?'
  12. )
  13. }
  14. mongoose.set('autoIndex', false)
  15. mongoose.set('strictQuery', false)
  16. const connectionPromise = mongoose.connect(
  17. Settings.mongo.url,
  18. Settings.mongo.options
  19. )
  20. connectionPromise.then(mongooseInstance => {
  21. Metrics.mongodb.monitor(mongooseInstance.connection.client)
  22. })
  23. addConnectionDrainer('mongoose', async () => {
  24. await connectionPromise
  25. await mongoose.disconnect()
  26. })
  27. mongoose.connection.on('connected', () =>
  28. logger.debug('mongoose default connection open')
  29. )
  30. mongoose.connection.on('error', err =>
  31. logger.err({ err }, 'mongoose error on default connection')
  32. )
  33. mongoose.connection.on('disconnected', () =>
  34. logger.debug('mongoose default connection disconnected')
  35. )
  36. if (process.env.MONGOOSE_DEBUG) {
  37. mongoose.set('debug', (collectionName, method, query, doc) =>
  38. logger.debug({ collectionName, method, query, doc }, 'mongoose debug')
  39. )
  40. }
  41. mongoose.plugin(schema => {
  42. schema.options.usePushEach = true
  43. })
  44. mongoose.Promise = global.Promise
  45. async function getMongoClient() {
  46. const mongooseInstance = await connectionPromise
  47. return mongooseInstance.connection.getClient()
  48. }
  49. async function getNativeDb() {
  50. const mongooseInstance = await connectionPromise
  51. return mongooseInstance.connection.db
  52. }
  53. mongoose.getMongoClient = getMongoClient
  54. mongoose.getNativeDb = getNativeDb
  55. mongoose.connectionPromise = connectionPromise
  56. module.exports = mongoose