mongoose-utils.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import mongoose, {
  2. Model, Document, ConnectionOptions, Schema,
  3. } from 'mongoose';
  4. export const initMongooseGlobalSettings = (): void => {
  5. // supress deprecation warnings
  6. // see: https://mongoosejs.com/docs/deprecations.html
  7. mongoose.set('useFindAndModify', false);
  8. mongoose.set('useCreateIndex', true);
  9. };
  10. export const getMongoUri = (): string => {
  11. const { env } = process;
  12. return env.MONGOLAB_URI // for B.C.
  13. || env.MONGODB_URI // MONGOLAB changes their env name
  14. || env.MONGOHQ_URL
  15. || env.MONGO_URI
  16. || ((env.NODE_ENV === 'test') ? 'mongodb://mongo/growi_test' : 'mongodb://mongo/growi');
  17. };
  18. export const getModelSafely = <T>(modelName: string): Model<T & Document> | null => {
  19. if (mongoose.modelNames().includes(modelName)) {
  20. return mongoose.model<T & Document>(modelName);
  21. }
  22. return null;
  23. };
  24. export const getOrCreateModel = <Interface, Method>(modelName: string, schema: Schema<Interface>): Method & Model<Interface & Document> => {
  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. // see: https://mongoosejs.com/docs/deprecations.html
  32. export const mongoOptions: ConnectionOptions = {
  33. useNewUrlParser: true,
  34. useUnifiedTopology: true,
  35. };