[DATAMONGO-1997] Add support to return the single deleted item for a deleteBy query method Created: 04/Jun/18  Updated: 13/Feb/20  Resolved: 29/Jan/20

Status: Closed
Project: Spring Data MongoDB
Component/s: None
Affects Version/s: None
Fix Version/s: 3.0 M3 (Neumann)

Type: Improvement Priority: Major
Reporter: Eugene Tenkaev Assignee: Christoph Strobl
Resolution: Complete Votes: 0
Labels: lovelace
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Last updater: Mark Paluch
Pull Request URL: https://github.com/spring-projects/spring-data-mongodb/pull/826
Sprint: Lovelace RC1, Lovelace GA, Lovelace SR1, Moore RC1, Moore RC2, Moore SR1, Moore SR2, Neumann M3

 Description   

Please add possibility to delete and return only one item.
Right now it possible to delete and return list of deleted items. For example:

public interface PersonRepository extends MongoRepository<Person, String> {
  List<Person> deleteByLastname(String lastname);     
}

But it will be great to have possibility to get only one item if it exists. So it also provides possibiltiy to nicely handle in the REST api situations when user reqeusted deletion of the item that dosen't exists.

So the methods will looks like:

public interface PersonRepository extends MongoRepository<Person, String> {
    Optional<Person> deleteByLastname(String lastname);

    Optional<Person> deleteById(String id);
}


 Comments   
Comment by Oliver Drotbohm [ 04/Jun/18 ]

That's a nice idea, Eugene. Note, that as a temporal workaround you can check the list for emptiness or even use long as return type and check for 0 if all you're interested in is whether the method invocation didn't actually end up in a delete.

Comment by Eugene Tenkaev [ 04/Jun/18 ]

@olivergierke thanks, for the fast push.

My business requirement was to return deleted entity in JSON. And if no entity is deleted - then send 404.
And as you suggested workaround I used check on emptiness, if it's empty return 404, if no - serialize to the POJO first item.
But this add some boilerplate code, so I'm decided to go here.

Right now I think this is even more related to the core org.springframework.data.repository.Repository, org.springframework.data.repository.CrudRepository please check if I'm wrong.

This will also nice addition for the spring-data-rest (wich I'm use).

Generated at Fri Jul 10 07:14:01 UTC 2020 using Jira 8.5.4#805004-sha1:0444eab799707f9ad7b248d69f858774aadfd250.