mongoose-utils.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import mongoose from 'mongoose';
  2. import type {
  3. Model, Document, Schema, ConnectOptions,
  4. } from 'mongoose';
  5. // suppress DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version
  6. type ConnectionOptionsExtend = {
  7. useUnifiedTopology: boolean
  8. }
  9. // No More Deprecation Warning Options
  10. // Removed useFindAndModify and useCreateIndex option
  11. // see: https://mongoosejs.com/docs/migrating_to_6.html#no-more-deprecation-warning-options
  12. export const initMongooseGlobalSettings = (): void => {};
  13. export const getMongoUri = (): string => {
  14. const { env } = process;
  15. return env.MONGOLAB_URI // for B.C.
  16. || env.MONGODB_URI // MONGOLAB changes their env name
  17. || env.MONGOHQ_URL
  18. || env.MONGO_URI
  19. || ((env.NODE_ENV === 'test') ? 'mongodb://mongo/growi_test' : 'mongodb://mongo/growi');
  20. };
  21. export const getModelSafely = <T>(modelName: string): Model<T & Document> | null => {
  22. if (mongoose.modelNames().includes(modelName)) {
  23. return mongoose.model<T & Document>(modelName);
  24. }
  25. return null;
  26. };
  27. export const getOrCreateModel = <Interface, Method>(modelName: string, schema: Schema<Interface>): Method & Model<Interface & Document> => {
  28. if (mongoose.modelNames().includes(modelName)) {
  29. return mongoose.model<Interface & Document, Method & Model<Interface & Document>>(modelName);
  30. }
  31. return mongoose.model<Interface & Document, Method & Model<Interface & Document>>(modelName, schema);
  32. };
  33. // supress deprecation warnings
  34. // useNewUrlParser no longer necessary
  35. // see: https://mongoosejs.com/docs/migrating_to_6.html#no-more-deprecation-warning-options
  36. export const mongoOptions: ConnectOptions & ConnectionOptionsExtend = {
  37. useUnifiedTopology: true,
  38. };