Duplicate key error when Patching

Hey, i have an issue when i want to patch update existing object in Spring Rest API project. I know that in database i have one object with unique ID and when i want to patch it i get duplicate key error. I know that mongoDB “save” method should update object when it exists by id and put new object when it doesn’t.

here is some code:

    @Override
    public Optional<Budget> updateBudgetContent(BudgetId budgetId,
                                                Optional<String> title,
                                                Optional<BigDecimal> limit,
                                                Optional<TypeOfBudget> typeOfBudget,
                                                Optional<BigDecimal> maxSingleExpense,
                                                String userId
    ) {
        budgetRepository.findBudgetByBudgetIdAndUserId(budgetId, userId).map(
                budgetFromRepository -> new Budget(budgetId,
                        title.orElseGet(budgetFromRepository::title),
                        limit.orElseGet(budgetFromRepository::limit),
                        typeOfBudget.orElseGet(budgetFromRepository::typeOfBudget),
                        maxSingleExpense.orElseGet(budgetFromRepository::maxSingleExpense),
                        userId
                )).ifPresent(budgetRepository::save);
        return budgetRepository.findBudgetByBudgetIdAndUserId(budgetId, userId);
    }

the “BudgetId” object has just String value field.

Ok i found the solution. I had to replace @Id to @MongoId in domain class. eot

1 Like