all! I’m working on a project with MongoDB and Spring Boot. I want to implement a feature so that once I start running the server, there will be a fixed item (or file) stored in the collection of the MongoDB database. I want to forbid remove operation for this collection from application. How could I achieve this function? If there is any ambiguity, please let me know.
Here is an example. Let’s say that there is a collection called Node
. This is the schema
:
{
"id": "xxxx",
"value": "1",
"left": "left_node",
"right": "right_node"
}
I want to keep this data in the database once the server started.
2
Answers
anything can be removed within a database. but you can manage that by create separate users with different
roles/privileges
when accessing the database. ref: create-a-user-defined-rolebut you can do it manually where you need to check the
_id|id
before or within operation delete,ex:
Assuming, you’re using Spring Data Mongo, if you need to forbid delete operations on your collection, you can create a special repository interface and inherit the repository bean for that collection from that repository interface.
Declare a generic repository which allows only
save()
operation:Note: Dont forget to annotate this generic repository with
@NoRepositoryBean
which is used to avoid creating repository proxies for interfaces that actually match the criteria of a repo interface but are not intended to be one.And extend your repository bean for that collection from that interface. Also add a
existsByValue()
method for further checking during the application startup.Then you can create a listener that listens for
ApplicationReadyEvent
Within this listener you can check if the
Node
exists. If it doesn’t, then you save a document.