{"id":14956620,"url":"https://github.com/mongodb/mongodb-vapor","last_synced_at":"2025-10-19T07:31:19.661Z","repository":{"id":43153199,"uuid":"318459888","full_name":"mongodb/mongodb-vapor","owner":"mongodb","description":"MongoDB + Vapor integration","archived":false,"fork":false,"pushed_at":"2023-07-30T10:33:58.000Z","size":12075,"stargazers_count":38,"open_issues_count":1,"forks_count":8,"subscribers_count":23,"default_branch":"main","last_synced_at":"2025-01-31T05:44:49.011Z","etag":null,"topics":["mongodb","swift","vapor"],"latest_commit_sha":null,"homepage":"https://mongodb.github.io/mongodb-vapor/","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mongodb.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-12-04T09:01:34.000Z","updated_at":"2024-01-24T07:22:45.000Z","dependencies_parsed_at":"2024-08-05T19:33:40.621Z","dependency_job_id":null,"html_url":"https://github.com/mongodb/mongodb-vapor","commit_stats":{"total_commits":40,"total_committers":5,"mean_commits":8.0,"dds":0.6,"last_synced_commit":"7de4f7aea34ac4fd96ac7b52fb97933361212a84"},"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongodb%2Fmongodb-vapor","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongodb%2Fmongodb-vapor/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongodb%2Fmongodb-vapor/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mongodb%2Fmongodb-vapor/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mongodb","download_url":"https://codeload.github.com/mongodb/mongodb-vapor/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":236738684,"owners_count":19196962,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["mongodb","swift","vapor"],"created_at":"2024-09-24T13:13:13.641Z","updated_at":"2025-10-19T07:31:14.379Z","avatar_url":"https://github.com/mongodb.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"# MongoDBVapor\nA library for building applications with [MongoDB](https://www.mongodb.com/) + [Vapor](https://vapor.codes/).\n\n- [Documentation](#documentation)\n- [Bugs / Feature Requests](#bugs---feature-requests)\n- [Installation](#installation)\n  * [Step 1: Install Required System Libraries (Linux Only)](#step-1-install-required-system-libraries-linux-only)\n  * [Step 2: Install MongoDBVapor](#step-2-install-mongodbvapor)\n    - [Create a new project from a template](#create-a-new-project-from-a-template)\n    - [Add to a project manually](#add-to-a-project-manually)\n- [Docker Usage](#docker-usage)\n- [Example Usage](#example-usage)\n  * [Configure global settings](#configure-global-settings)\n  * [Use MongoDB in a Request Handler](#use-mongodb-in-a-request-handler)\n      * [Async/Await APIs](#asyncawait-apis)\n      * [`EventLoopFuture` APIs](#eventloopfuture-apis)\n  * [Perform one-time setup or teardown code](#perform-one-time-setup-or-teardown-code)\n  * [Working with Extended JSON](#working-with-extended-json)\n\n## Documentation\n### The latest documentation for the library is available [here](https://mongodb.github.io/mongodb-vapor/).\n\n### You can find a complete example project built using this library [here](https://github.com/mongodb/mongo-swift-driver/tree/main/Examples/VaporExample)!\n\n## Bugs / Feature Requests\nThink you've found a bug? Want to see a new feature in `mongodb-vapor`? Please open a case in our issue management tool, JIRA:\n\n1. Create an account and login: [jira.mongodb.org](https://jira.mongodb.org)\n2. Navigate to the SWIFT project: [jira.mongodb.org/browse/SWIFT](https://jira.mongodb.org/browse/SWIFT)\n3. Click **Create Issue** - Please provide as much information as possible about the issue and how to reproduce it.\n\nBug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the\nCore Server (i.e. SERVER) project are **public**.\n\n## Installation\nThis library works with **Swift 5.2+** , and supports Linux and macOS usage. The minimum macOS version required is **10.15**.\n\nInstallation is supported via [Swift Package Manager](https://swift.org/package-manager/).\n\n### Step 1: Install Required System Libraries (Linux Only)\nIf you are using macOS, you can skip ahead.\n\nThe driver vendors and wraps the MongoDB C driver (`libmongoc`), which depends on a number of external C libraries when built in Linux environments. As a result, these libraries must be installed on your system in order to build MongoSwift.\n\nTo install those libraries, please follow the [instructions](http://mongoc.org/libmongoc/current/installing.html#prerequisites-for-libmongoc) from `libmongoc`'s documentation.\n\n### Step 2: Install MongoDBVapor\n\n#### Create a New Project From a Template\nTo create a new project using the library, the easiest way to get started is by using\nVapor's command line tool, [Vapor Toolbox](https://github.com/vapor/toolbox), along with our application template:\n```\nvapor new MyProject --template https://github.com/mongodb/mongodb-vapor-template/\n```\nThis will create a new project from a template, which you can edit to your liking. See the instructions [here](https://github.com/mongodb/mongodb-vapor-template/blob/main/README.md) or in the generated README for more details on the generated project.\n#### Add to a Project Manually\nAlternatively, you can integrate this library manually in a SwiftPM project by adding it along with Vapor as dependencies in your project's `Package.swift` file:\n\n```swift\n// swift-tools-version:5.2\nimport PackageDescription\n\nlet package = Package(\n    name: \"VaporExample\",\n    platforms: [\n        .macOS(.v10_15)\n    ],\n    dependencies: [\n        .package(url: \"https://github.com/vapor/vapor\", .upToNextMajor(from: \"4.7.0\")),\n        .package(url: \"https://github.com/mongodb/mongodb-vapor\", .upToNextMajor(from: \"1.1.0\"))\n    ],\n    targets: [\n        .target(\n            name: \"App\",\n            dependencies: [\n                .product(name: \"Vapor\", package: \"vapor\"),\n                .product(name: \"MongoDBVapor\", package: \"mongodb-vapor\")\n            ]\n        ),\n        .target(name: \"Run\", dependencies: [\n            .target(name: \"App\"),\n            .product(name: \"MongoDBVapor\", package: \"mongodb-vapor\")\n        ])\n    ]\n)\n```\n\nThen run `swift build` to download, compile, and link all your dependencies.\n\n## Docker Usage\nNote that if you are using this library on Docker with Vapor's default Docker template file, you'll need to install the system\ndependencies the driver requires on Linux, as mentioned [above](#step-1-install-required-system-libraries-linux-only).\n\nTo do this, add the following to your Dockerfile:\n```\nRUN apt-get update \u0026\u0026 apt-get install -y libssl-dev\n```\n\nA user [@dotmain](https://github.com/dotmain) has also created a Vapor template that includes Docker configuration [here](https://github.com/dotmain/native-mongo-vapor-template).\n\n## Example Usage\n### You can find a complete example project built using this library [here](https://github.com/mongodb/mongo-swift-driver/tree/main/Examples/VaporExample). \n\nTo summarize the available features:\n\n### Configure global settings\n\nIn your `configure(_:)` method in `App/configure.swift`, add:\n```swift\n// Configure the app for using a MongoDB server at the provided connection string.\ntry app.mongoDB.configure(\"mongodb://localhost:27017\")\n```\n\nIn `Run/main.swift`, add:\n```swift\nimport MongoDBVapor\n\ndefer {\n    // Cleanup the application's MongoDB data.\n    app.mongoDB.cleanup()\n    // Clean up the driver's global state. The driver will no longer be usable from this program after this method is\n    // called.\n    cleanupMongoSwift()\n}\n```\n\n### Use MongoDB in a Request Handler\n\n#### Async/Await APIs\nFor collections you plan to access frequently, we recommend adding computed properties in an extension to `Request`\nto provide easy access, like:\n```swift\nextension Request {\n    /// A collection with an associated `Codable` type `Kitten`.\n    var kittenCollection: MongoCollection\u003cKitten\u003e {\n        self.application.mongoDB.client.db(\"home\").collection(\"kittens\", withType: Kitten.self)\n    }\n}\n```\n\nYou can then use these in request handlers as follows:\n```swift\n/// Handles a request to load the list of kittens.\napp.get(\"kittens\") { req async throws -\u003e [Kitten] in\n    try await req.kittenCollection.find().toArray()\n}\n\n/// Handles a request to add a new kitten.\napp.post(\"kittens\") { req async throws -\u003e Response in\n    let newKitten = try req.content.decode(Kitten.self)\n    try await req.kittenCollection.insertOne(newKitten)\n    return Response(status: .created)\n}\n```\n\n#### `EventLoopFuture` APIs\nFor collections you plan to access frequently, we recommend adding computed properties in an extension to `Request`\nto provide easy access, like:\n```swift\nextension Request {\n    /// A collection with an associated `Codable` type `Kitten`.\n    var kittenCollection: MongoCollection\u003cKitten\u003e {\n        self.mongoDB.client.db(\"home\").collection(\"kittens\", withType: Kitten.self)\n    }\n}\n```\n\n**Any client, database, or collection object you access via `Request.mongoDB` will automatically return `EventLoopFuture`s \non the same `EventLoop` the `Request` is being handled on, simplifying thread safety concerns and improving performance\nby removing the need to `hop` the returned futures.**\n\nYou can then use these in request handlers as follows:\n```swift\n/// Handles a request to load the list of kittens.\napp.get(\"kittens\") { req -\u003e EventLoopFuture\u003c[Kitten]\u003e in\n    req.kittenCollection.find().flatMap { cursor in\n        cursor.toArray()\n    }\n}\n\n/// Handles a request to add a new kitten.\napp.post(\"kittens\") { req -\u003e EventLoopFuture\u003cResponse\u003e in\n    let newKitten = try req.content.decode(Kitten.self)\n    return req.kittenCollection.insertOne(newKitten)\n        .map { _ in Response(status: .created) }\n}\n```\n\n### Perform one-time setup or teardown code\nIf you have one-time code you'd like to run each time your application starts up, e.g. in `Run/main.swift`, you can\nuse the global client, accessible via `Application.mongoDB`:\n```swift\n// Configure the app for using a MongoDB server at the provided connection string.\ntry app.mongoDB.configure(\"mongodb://localhost:27017\")\nlet coll = app.mongoDB.client.db(\"home\").collection(\"kittens\")\n// creates a unique index if it doesn't exist already.\n_ = try coll.createIndex([\"name\": 1], indexOptions: IndexOptions(unique: true)).wait()\n```\n\n### Working with Extended JSON\nIf you'd like to use `ExtendedJSONEncoder` and `ExtendedJSONDecoder` for encoding/decoding JSON requests/responses, in  `App/configure.swift`, add:\n```swift\n// Use `ExtendedJSONEncoder` and `ExtendedJSONDecoder` for encoding/decoding `Content`.\nContentConfiguration.global.use(encoder: ExtendedJSONEncoder(), for: .json)\nContentConfiguration.global.use(decoder: ExtendedJSONDecoder(), for: .json)\n```\nNote that this is currently required if you want to use `BSONDocument` as a `Content` type and e.g.\ndirectly return `BSONDocument`s from request handlers, because `BSONDocument` does not yet support \nbeing encoded/decoded via `JSONEncoder` and `JSONDecoder`.\n\nFor more information on JSON interoperation in general with the driver, see our \n[JSON interop guide](https://mongodb.github.io/swift-bson/docs/current/SwiftBSON/json-interop.html).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmongodb%2Fmongodb-vapor","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmongodb%2Fmongodb-vapor","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmongodb%2Fmongodb-vapor/lists"}