CRUD Operations With Vapor 4 And MongoDB

Emmanuel Orvain
2 min readNov 6, 2020

--

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)

Connection between Vapor 4 and MongoDB

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.

Data model in Vapor 4

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.

Routes definition

Test your API with Postman

At this step you can launch the Vapor server, and check the API with Postman.

  1. Read the product list
Read the product list with Postman

2. Update your product

Update your product with Postman

If you enjoyed this post, please leave some claps. 👏👏👏

You can clap up to 50 times, so get clicking/tapping! 😉

--

--

Emmanuel Orvain
Emmanuel Orvain

Written by Emmanuel Orvain

French iOS / Android experimented developper from Toulouse in south of France. https://occirama.com/scanandfile/

No responses yet