If you have to implement an API with CRUD operations on MongoDB with Go, but with the caveat that the documents on a collection had to be deleted usin

How to Soft Delete with MongoDB and Go

submited by
Style Pass
2021-05-24 04:00:09

If you have to implement an API with CRUD operations on MongoDB with Go, but with the caveat that the documents on a collection had to be deleted using the soft delete pattern, then continue reading to find out how.

If you are using a SQL database this is a common and easy task, and probably easier if you do it on any other language with a framework . I searched about what was the best way to do this in MongoDB, and I found several implementation examples, but none of them were very clear or straightforward, and there were just a few examples in Go.

So, after looking at the official MongoDB driver for Go and the examples on the MongoDB documentation, it all ends up on having a well-defined struct for your document with the right json and bson attributes.

Notice how we are excluding this field from the json response with the - attribute because we don't want this to be returned as part of the response data, also take a look at the omitempty bson attribute, so this does not get into the document if it is not specified.

Leave a Comment