4

I have Spring data repository class that extends MongoRepository. So I'm doing a POST request to create a record that holds several reference fields to refer other documents.

The repository interface :

@RepositoryRestResource(collectionResourceRel = "user",path = "user")
 public interface UserRepository extends MongoRepository<User,String>{
}

The Model classes :

@Document(collection = "user")
public class User {
@Id
private String id;
private String email;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date createdTime;
@Field("infoSignups")
@DBRef
private InfoSignUp infoSignups;
@Field("webinarSignups")
@DBRef
private WebinarSignUp webinarSignups;

}

@Document(collection = "infoSignups")
public class InfoSignUp {

@Id
private String id;
private String email;

}

@Document(collection = "webinarSignups")
public class WebinarSignups {

@Id
private String id;
private String email;

}

The POST request :

{  
  "email":"sheen.example@gmail.com",
  "name":"test",
  "infoSignups":[  
    {  
     "id":"5cbeb33199a4640b94ba1de8"
     }
   ],
  "webinarSignups":[  
    {  
     "id":"5cc0136599a4641d835d3259"
    }
   ],
  "businessName":"test data",
  "phone":"test data",
  "address":"test data",
  "createdTime":"2015-09-26T01:30:00.000Z"
 }

But when I'm doing the POST request to the repository endpoint the reference fields are not saved, other fields are saved in the collection. Do I have to persist the object manually without using the Spring data? How can I save the references to the other collection using the POST request to the endpoint?

GeekySelene
  • 847
  • 3
  • 13
  • 31
  • I think this post [Custom Cascading in Spring Data MongoDB](https://www.baeldung.com/cascading-with-dbref-and-lifecycle-events-in-spring-data-mongodb) will be helpful... – Cepr0 Apr 27 '19 at 11:40

1 Answers1

0

Before version 3.3.0 of Spring Data MongoDB we need to retrieve the linked document on the base of Id and set that value.

If you are using the version number 3.3.0 or newer you can directly use the annotation @DocumentReference instead of @DBRef

For more details you can visit the https://bootify.io/mongodb/document-reference-in-spring-boot-mongodb.html

or

https://docs.spring.io/spring-data/mongodb/docs/3.4.0-M4/api/org/springframework/data/mongodb/core/mapping/DocumentReference.html

Rohit Mehlawat
  • 121
  • 1
  • 1
  • 6