sambit16
sambit16

Reputation: 68

Spring data deleteBy query doesnt return deleted object

In Spring-data-mongodb, can we return the single deleted object from query method of repository like below

public interface MyRepository extends MongoRepository<MyObject, String>{
 Optional<MyObject> deleteByXAndY(String x, String y);
}

if there will be always single document that's get deleted by above query.

I tried it but it throws exception like cant convert Long to MyObject. I think only void, long or List or Stream are supported. Is there any way to achieve what I am trying to do?

Upvotes: 2

Views: 440

Answers (1)

Mark B
Mark B

Reputation: 200486

Spring doesn't know that only one object can ever be deleted by this method, so it won't allow you to define it with a single result returned. After all, there is no guarantee in the "contract" you have defined here that there will only be one match. You should probably define the method to return a List and then just get the first object from the list if you are sure there will only be one.

Upvotes: 1

Related Questions