Ghiloufi
Ghiloufi

Reputation: 321

spring-data-mongodb delete function doesn't work?

I'm using spring-data -mongodb to do crud operations (create , read , update , delete), but the delete function doesn't work and I don't know why? . Here is my code.

import org.bson.types.Binary;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@ToString
@Getter
@Setter
@Document(collection = "patterns")
public class Pattern {
    @Id
    @Field
    private String id;
    @Field
    @Indexed(unique = true)
    private String name;
    @Field
    private String status;
    @Field
    private Binary patternFile;
}
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import fod.pfe7.administratorportal.domain.Pattern;
public interface PatternRepository extends MongoRepository<Pattern, String> {
    List<Pattern> findByName(String name);
}

in my controller I do .

patternRepository.findByName(patternName).forEach(pattern -> {
            patternRepository.deleteById(pattern.getId());
            result.put("status", 0);
            result.put("message", "pattern deleted successfuly");
        });

Upvotes: 0

Views: 1492

Answers (2)

Panachovo
Panachovo

Reputation: 21

Maybe a little late...

I got the same error and saw that the delete query did not include the Object_Id, so the findByID method was not working either.

The solution for me was to include the targetType in the @Field annotation:

@Field(name = "_id", targetType = FieldType.OBJECT_ID)

Upvotes: 0

Thanh Nhan
Thanh Nhan

Reputation: 493

Your data might have been created by other system, which use different presentation of "_id" (says String). With newer version of spring data mongodb, you can use @MongoId instead of @Id to control this.

In my case, the later deletes record correctly.

@Id private String id; produces

Remove using query: { "_id" : { "$oid" : "60ed51ce597826297941ade4"}} in collection: sample.

@MongoId(FieldType.STRING) private String id; produces

Remove using query: { "_id" : "60ed51ce597826297941ade4"} in collection: sample.

Upvotes: 0

Related Questions