mongoose-utils.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import mongoose from 'mongoose';
  2. import type {
  3. Model, Document, 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. export const getMongoUri = (): string => {
  10. const { env } = process;
  11. return env.MONGOLAB_URI // for B.C.
  12. || env.MONGODB_URI // MONGOLAB changes their env name
  13. || env.MONGOHQ_URL
  14. || env.MONGO_URI
  15. || ((env.NODE_ENV === 'test') ? 'mongodb://mongo/growi_test' : 'mongodb://mongo/growi');
  16. };
  17. export const getModelSafely = <T>(modelName: string): Model<T & Document> | null => {
  18. if (mongoose.modelNames().includes(modelName)) {
  19. return mongoose.model<T & Document>(modelName);
  20. }
  21. return null;
  22. };
  23. // TODO: Do not use any type
  24. export const getOrCreateModel = <Interface, Method>(modelName: string, schema: any): any => {
  25. if (mongoose.modelNames().includes(modelName)) {
  26. return mongoose.model<Interface & Document, Method & Model<Interface & Document>>(modelName);
  27. }
  28. return mongoose.model<Interface & Document, Method & Model<Interface & Document>>(modelName, schema);
  29. };
  30. // supress deprecation warnings
  31. // useNewUrlParser no longer necessary
  32. // see: https://mongoosejs.com/docs/migrating_to_6.html#no-more-deprecation-warning-options
  33. export const mongoOptions: ConnectOptions & ConnectionOptionsExtend = {
  34. useUnifiedTopology: true,
  35. };