This repo is deprecated. It still works but is not maintained. You are better off using MongoDB from the Swift Cloud team.
A simple Swift library to interact with MongDB Atlas via their Data API for Compute
This can all be easily hosted on Swift Cloud
Install MongoManager
.package(url: "https://github.com/SparrowTek/MongoManager", from: "1.0.6")Add it as a target dependency
.executableTarget(
name: "MyApp",
dependencies: ["MongoManager"]
)Create a global let property
let mongoData = MongoData(baseURL: "https://data.mongodb-api.com/app/data-abcde/endpoint/data/v1",
database: "database",
dataSource: "dataSource",
apiKey: try? Dictionary(name: "mongoDB").get("dataAPI"))Your baseURL will be provided to you by MongoDB Atlas. You will configure database and dataSource in Atlas. You will create an apiKey when you setup the MongoDB Atlas Data API. This sample code is extracting that key from a Dictionary hosted on Swift Cloud.
Now in your route,
struct MongoDBAtlasRoutes {
static func regiser(_ router: Router) {
router.post("/mongo/user", createUser)
}
static func createUser(req: IncomingRequest, res: OutgoingResponse) async throws {
// create the Codable user object from the req body
let user = try await req.body.decode(User.self)
do {
// use static insertOne method on MongoManager struct
_ = try await MongoManager.insertOne(mongoData: mongoData, collection: mongoCollection, document: user)
// report back to API
try await res.status(.created).send(user)
} catch {
// handle error
try await res.status(.internalServerError).send(error.localizedDescription)
}
}
}This POST route will create a User object from the request body and insert it into your MongoDB users collection.