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 untilApplication.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’sEventLoopGroup
. WithinRequest
handlers, it is preferable to useRequest.mongoDB.client
as that will return a client which uses the sameEventLoop
as theRequest
.Declaration
Swift
public var client: MongoClient { get }
-
Configures a global
MongoClient
with the specified options. The client may then be accessed via themongoDB.client
computed property on theApplication
. The client will use theApplication
‘sEventLoopGroup
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:
- A
MongoError.InvalidArgumentError
if the connection string passed in is improperly formatted.
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. - A
-
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()