skip to Main Content

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


  1. 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-role

    but you can do it manually where you need to check the _id|id before or within operation delete,

    ex:

    db.document.delete({id: {$ne: 'xxxx'}}}
    
    Login or Signup to reply.
  2. 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:

    @NoRepositoryBean
    public interface SaveOnlyRepository<T, ID> extends Repository<T, ID> {
    
        <S extends T> S save(S entity);
    }
    

    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.

    public interface NodeRepository extends SaveOnlyRepository<Node, String> {
    
        boolean existsByValue(String value);
    }
    

    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.

    @Component
    public class Listener {
    
        private final NodeRepository nodeRepository;
    
        public Listener(NodeRepository nodeRepository) {
            this.nodeRepository = nodeRepository;
        }
    
        @EventListener(ApplicationReadyEvent.class)
        public void init() {
            if (!nodeRepository.existsByValue("1")) {
                nodeRepository.save(...);
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search