mongoose-utils.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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 = <Interface, Method = Interface>(modelName: string): Method & Model<Interface & Document> | null => {
  18. if (mongoose.modelNames().includes(modelName)) {
  19. return mongoose.model<Interface & Document, Method & Model<Interface & Document>>(modelName);
  20. }
  21. return null;
  22. };
  23. // TODO: Do not use any type
  24. export const getOrCreateModel = <Interface, Method>(modelName: string, schema: any): Method & Model<Interface & Document> => {
  25. return getModelSafely(modelName) ?? mongoose.model<Interface & Document, Method & Model<Interface & Document>>(modelName, schema);
  26. };
  27. // supress deprecation warnings
  28. // useNewUrlParser no longer necessary
  29. // see: https://mongoosejs.com/docs/migrating_to_6.html#no-more-deprecation-warning-options
  30. export const mongoOptions: ConnectOptions & ConnectionOptionsExtend = {
  31. useUnifiedTopology: true,
  32. };