MongoDB

public struct MongoDB

A type providing access to MongoDB APIs for use at the Application level.

  • A global MongoClient for use throughout the application. This client is not accessible until Application.mongoDB.configure() has been called.

    If you are using Vapor’s async/await APIs: This client should be used throughout your application, including in request handlers, via Request.application.mongoDB.client.

    If you are using Vapor’s EventLoopFuture APIs: This client is primarily intended for use in application setup/teardown code and may return futures on any event loop within the application’s EventLoopGroup. Within Request handlers, it is preferable to use Request.mongoDB.client as that will return a client which uses the same EventLoop as the Request.

    Declaration

    Swift

    public var client: MongoClient { get }
  • Configures a global MongoClient with the specified options. The client may then be accessed via the mongoDB.client computed property on the Application. The client will use the Application‘s EventLoopGroup for executing operations.

    For example:

      let app = Application() // a Vapor Application
      try app.mongoDB.configure() // configures a MongoClient
      app.mongoDB.client.listDatabases() // a client is now accessible via the Application
    

    Throws

    Throws:

    Declaration

    Swift

    public func configure(
        _ connectionString: String = "mongodb://localhost:27017",
        options: MongoClientOptions? = nil
    ) throws

    Parameters

    connectionString

    the connection string to connect to.

    options

    optional MongoClientOptions to use for the client.

  • Handles MongoDB related cleanup. Call this method when shutting down your application. If an error occurs while closing the client, it will be logged via the Application‘s logger. For example:

      app.mongoDB.cleanup()
      app.shutdown()
    

    It is an error to attempt to use the driver after calling this method.

    Declaration

    Swift

    public func cleanup()