Tutorial: How to use MongoDB
In this tutorial youβll learn how to use MongoDB with your project β¨ π π
You can find the result of this tutorial on github here
This tutorial is a natural follow-up of How to write Controllers. You can either go for that tutorial first and come back later or be a rebel, skip it and read on π
Index
1. Install Homebrew
2. Install MongoDB
3. Create and generate a new project
4. Configure your project to use MongoDB
1. Install Homebrew
If you donβt have it yet I highly recommend to get it. It makes it super easy for you to install dependencies like MongoDB. To install Homebrew execute the following in your terminal:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
We will also install brew services. It will make it incredibly easy to start the MongoDB server and let it start alongside with your mac! Thatβs awesome β¨!
brew tap homebrew/services
Now whenever you want to know what services are running just execute:
brew services list
2. Install MongoDB
Installing MongoDB with Homebrew is so easy, what am I even here for π?
brew install mongodb
Thatβs it. Done. Now to start mongodb just execute the following command:
brew services start mongodb
See how easy brew services makes it? mongodb now starts alongside your mac!
We donβt have to create a database manually. In fact defining our database configuration within our project with a database name that very database will be created as soon as data is inserted. And we do insert data when we submit a name for our userlist under /user βπ»π€
Terminal Cheatsheet:
connect to mongodb server: mongo
within server, list databases: show dbs
within server, exit server: quit()
Alrighty! You are ready for step 3. Create and generate a new project π
3. Create and generate a new project
We will use the outcome of the tutorial mentioned in the beginning as a template to create our new project:
vapor new projectName --template=vaporberlin/my-first-controller --branch=vapor-2
Before we generate an Xcode project we would have to change the package name within Package.swift:
// swift-tools-version:4.0import PackageDescriptionlet package = Package(
name: "projectName", // changed
products: [
.library(name: "App", targets: ["App"]),
.executable(name: "Run", targets: ["Run"])
],dependencies: [
.package(url: "https://github.com/vapor/vapor.git", .upToNextMajor(from: "2.1.0")),
.package(url: "https://github.com/vapor/leaf-provider.git", .upToNextMajor(from: "1.1.0")),
.package(url: "https://github.com/vapor/fluent-provider.git", .upToNextMajor(from: "1.3.0")),
.package(url: "https://github.com/vapor-community/mongo-provider.git", .upToNextMajor(from: "2.0.0")) // added
],targets: [
.target(name: "App", dependencies: ["Vapor", "LeafProvider", "FluentProvider", "MongoProvider"],
exclude: [
"Config",
"Public",
"Resources",
]),.target(name: "Run", dependencies: ["App"]),
.testTarget(name: "AppTests", dependencies: ["App", "Testing"])
]
)
Now in the terminal at the root directory projectName/ execute:
vapor update -y
It may take a bit fetching the dependency, but when done you should have a project structure like this:
projectName/
βββ Package.swift
βββ Sources/
β βββ App/
β β βββ Controllers/
β β β βββ UserController.swift
β β βββ Models/
β β β βββ User.swift
β β βββ Routes/
β β β βββ Routes.swift
β β βββ Setup/
β β βββ Config+Setup.swift
β β βββ Droplet+Setup.swift
β βββ Run/
βββ Tests/
βββ Config/
βββ Resources/
βββ Public/
βββ Dependencies/
βββ Products/
If you now cmd+r or run we should be able to access the /user route π!
4. Configure your project to use MongoDB
Now all we need is a configuration file that holds our database information. Create a new Folder within Config/ and name it secrets/ so our database configuration file wonβt be tracked by git.
Within Config/secrets/ create a file and name it mongo.json and insert the following configuration:
{
"url": "mongodb://127.0.0.1:27017/mycooldb"
}
NOTE Hereβs the full possible configuration in case youβve a user and password: βmongodb://<db-user>:<db-pw>@<host>:<port>/<database>β
Finally weβll tell fluent to use mongodb as a driver. So in Config/fluent.json:
{
... "driver": "mongo", ...
}
Lastly weβll add the MongoProvider within Setup/Config+Setup.swift:
import LeafProvider
import FluentProvider
import MongoProvider // addedextension Config {
public func setup() throws {
try setupProviders()
try setupPreparations()
}private func setupProviders() throws {
try addProvider(LeafProvider.Provider.self)
try addProvider(FluentProvider.Provider.self)
try addProvider(MongoProvider.Provider.self) // added
}private func setupPreparations() throws {
preparations.append(User.self)
}
}
Our final cmd+r or run and refresh of /user and thatβs it! You successfully configured your project to use a mongodb database π π π