mongodbspring-bootspring-data-mongodbdbref

Get Embed Document based on DBRef in MongoDB using Spring data


I'm developing a spring boot application. I've 2 models that is

PersonEntity

@Data
@Document(collection = "products")
public class ProductEntity implements Serializable {

    private static final long serialVersionUID = -8118791879505582652L;

    @MongoId(FieldType.STRING)
    private String id;

    @Indexed
    @Field("name")
    private String name;
    
    @Field("category")
    @DBRef(lazy = true)
    private CategoryEntity category;
    
    // getters and setters
}

CategoryEntity

@Data
@Document(collection = "categories")
public class CategoryEntity implements Serializable {

    private static final long serialVersionUID = -636356399519451958L;

    @MongoId(value = FieldType.STRING)
    private String id;

    @Field("name")
    private String name;

    @Field("desc")
    private String desc;
    
    public CategoryEntity(String id) {
        super();
        this.id = id;
    }
    // getters and setters
}

when I'm saving data into DB then stored data is

Products Document

{
    "_id": {
        "$oid": "6141eeab92432109463ae8c4"
    },
    "name": "Adidas Running Shoes",
    "category": {
        "$ref": "categories",
        "$id": "614049d91042cf40b5b9b304"
    }
}

Categories Document

{
    "_id": {
        "$oid": "614049d91042cf40b5b9b304"
    },
    "name": "Shoes",
    "desc": "Men's running Shoes",
}

But when I'm try to findAll() the ProductEntity the data by using Spring-Data-MongoDB the category will return null.

public List<ProductModel> getProducts() {
    List<ProductEntity> entities = productRepo.findAll();
    return entities.stream().map(entity -> {
        ProductModel product = new ProductModel();
        BeanUtils.copyProperties(entity, product);
        if (Objects.nonNull(entity.getCategory())) {
            BeanUtils.copyProperties(entity.getCategory(), product.getCategory());
        }
        return product;
    }).collect(Collectors.toList());
}

and I need the output will be in below format.

{
    "_id": {
        "$oid": "6141eeab92432109463ae8c4"
    },
    "name": "Adidas Running Shoes",
   
    "category": {
        "_id": {
            "$oid": "614049d91042cf40b5b9b304"
        },
        "name": "Shoes",
        "desc": "Men's running Shoes",
    }
}

Please let me know how to get desired output.


Solution

  • I've done a minor change and issue has been resolved. I've changed

    from

    @MongoId(value = FieldType.STRING)
    private String id; 
    

    to

    @MongoId(value = FieldType.OBJECT_ID) 
    private ObjectId id;
    

    in the both entities and code works!