mongoose-utils.ts 1.7 KB

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