mongoose#ConnectOptions TypeScript Examples

The following examples show how to use mongoose#ConnectOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: app.ts    From tams-club-cal with MIT License 5 votes vote down vote up
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true } as ConnectOptions);
Example #2
Source File: connect.ts    From payload with MIT License 5 votes vote down vote up
connectMongoose = async (
  url: string,
  options: ConnectOptions,
  local: boolean,
  logger: pino.Logger,
): Promise<void> => {
  let urlToConnect = url;
  let successfulConnectionMessage = 'Connected to Mongo server successfully!';
  const connectionOptions = {
    ...options,
    useNewUrlParser: true,
    autoIndex: true,
  };

  if (process.env.NODE_ENV === 'test' || process.env.MEMORY_SERVER) {
    if (local) {
      urlToConnect = `${connection.url}:${connection.port}/${connection.name}`;
    } else {
      connectionOptions.dbName = 'payloadmemory';
      // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires
      const { MongoMemoryServer } = require('mongodb-memory-server');
      const mongo = await MongoMemoryServer.create({
        instance: {
          dbName: connection.name,
          port: connection.port,
        },
      });

      urlToConnect = mongo.getUri();
      successfulConnectionMessage = 'Connected to in-memory Mongo server successfully!';
    }
  }


  try {
    await mongoose.connect(urlToConnect, connectionOptions);
    logger.info(successfulConnectionMessage);
  } catch (err) {
    logger.error(`Error: cannot connect to MongoDB. Details: ${err.message}`, err);
    process.exit(1);
  }
}
Example #3
Source File: index.ts    From graphql-mesh with MIT License 4 votes vote down vote up
async getMeshSource(): Promise<MeshSource> {
    if (this.config.connectionString) {
      connect(this.config.connectionString, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      } as ConnectOptions).catch(e => console.error(e));

      await this.pubsub.subscribe('destroy', () => disconnect());
    }

    const schemaComposer = new SchemaComposer();
    await Promise.all([
      Promise.all(
        this.config.models?.map(async modelConfig => {
          const model = await loadFromModuleExportExpression<Model<Document<any, any, any>>>(modelConfig.path, {
            defaultExportName: modelConfig.name,
            cwd: this.baseDir,
            importFn: this.importFn,
          });
          if (!model) {
            throw new Error(`Model ${modelConfig.name} cannot be imported ${modelConfig.path}!`);
          }
          const modelTC = composeWithMongoose(model, modelConfig.options as any);
          await Promise.all([
            Promise.all(
              modelQueryOperations.map(async queryOperation =>
                schemaComposer.Query.addFields({
                  [`${modelConfig.name}_${queryOperation}`]: modelTC.getResolver(queryOperation),
                })
              )
            ),
            Promise.all(
              modelMutationOperations.map(async mutationOperation =>
                schemaComposer.Mutation.addFields({
                  [`${modelConfig.name}_${mutationOperation}`]: modelTC.getResolver(mutationOperation),
                })
              )
            ),
          ]);
          if (this.config.autoTypeMerging) {
            modelTC.setDirectiveByName('key', {
              selectionSet: /* GraphQL */ `
                {
                  id
                }
              `,
            });
            modelTC.setFieldDirectiveByName(`${modelConfig.name}_dataLoaderMany`, 'merge');
          }
        }) || []
      ),
      Promise.all(
        this.config.discriminators?.map(async discriminatorConfig => {
          const discriminator = await loadFromModuleExportExpression<any>(discriminatorConfig.path, {
            defaultExportName: discriminatorConfig.name,
            cwd: this.baseDir,
            importFn: this.importFn,
          });
          const discriminatorTC = composeWithMongooseDiscriminators(discriminator, discriminatorConfig.options as any);
          await Promise.all([
            Promise.all(
              modelQueryOperations.map(async queryOperation =>
                schemaComposer.Query.addFields({
                  [`${discriminatorConfig.name}_${queryOperation}`]: discriminatorTC.getResolver(queryOperation),
                })
              )
            ),
            Promise.all(
              modelMutationOperations.map(async mutationOperation =>
                schemaComposer.Mutation.addFields({
                  [`${discriminatorConfig.name}_${mutationOperation}`]: discriminatorTC.getResolver(mutationOperation),
                })
              )
            ),
          ]);
          if (this.config.autoTypeMerging) {
            discriminatorTC.setDirectiveByName('key', {
              selectionSet: /* GraphQL */ `
                {
                  id
                }
              `,
            });
            discriminatorTC.setFieldDirectiveByName(`${discriminatorConfig.name}_dataLoaderMany`, 'merge');
          }
        }) || []
      ),
    ]);

    // graphql-compose doesn't add @defer and @stream to the schema
    specifiedDirectives.forEach(directive => schemaComposer.addDirective(directive));

    if (this.config.autoTypeMerging) {
      const defaultStitchingDirectives = stitchingDirectives();
      defaultStitchingDirectives.allStitchingDirectives.forEach(directive => schemaComposer.addDirective(directive));
    }

    const schema = schemaComposer.buildSchema();

    return {
      schema,
    };
  }