CRUD Operations With Vapor 4 And MongoDB
This article focuses on how to build CRUD operations on VAPOR 4 with a MongoDB database. You will get source code to build a simple Vapor test project.
I am new to Vapor 4 and MongoDB. I come from iOS development, iOS and Vapor share the same programming language : Swift. For me, it’s easier to create a mobile application and backend server with the same programming language. I don’t have to learn a new programming language.
I also start to develop an application in Kotlin language. Kotlin is similar to Swift. Now, with 2 languages, we are able to create backend server and native applications to support all smartphones.
Connect Vapor 4 with MongoDB
# 1 Start MongoDB server
mongod — config /usr/local/etc/mongod.conf — fork
Make sure that your MongoDB instance is running on your localhost at port 27017 (default port)
Build your data model
The data model lets you configure the collection name and the keys. The following example is very simple. The model is a product with a name and a price.
The id type of the model is ObjectId. It’s recommended by Vapor 4. This is specific to MongoDB; I tried to set UUID type or String type, but none of them works. I encountered crash in the find() methods after some tests.
Build the CRUD methods
The following example shows how you Create, Read, Update and Delete a product from database.
Build the CRUD routes
The routes function lets you associate URL with the CRUD operation on the product that we define earlier.
Test your API with Postman
At this step you can launch the Vapor server, and check the API with Postman.
- Read the product list
2. Update your product
If you enjoyed this post, please leave some claps. 👏👏👏
You can clap up to 50 times, so get clicking/tapping! 😉