I'm learning how to use MongoDB with spring boot (Spring data MondoDB).
In my current code base that uses PostgreSQL, I have an API GET /api/orders/238392, which returns a model as follows:
{
"orderId":238392,
"status":"FULFILLED",
"senNumber":"AB8893920",
"customer":{
"customerId":"lskj2409023471lskdjflsf",
"name":"John Doe",
"email":"john.doe@acme.com",
"phoneNumber":"7326585306",
"city":"Los Angeles"
}
}
I now want to implement this user-case with MongoDB in the backend. This is my model
// Orders.java
@Data
@Document
public class Order {
@Id
private Long orderId;
private String status;
private String senNumber;
private Customer customer;
}
//Customer.java
@Data
@Document
public class Customer {
@Id
private String customerId;
private String name;
private String email;
private String phoneNumber;
private String city;
}
My API now works fine. However, I have a problem with the relationship between Orders and Customers.
In a relational world, I had the @ManyToOne on customer, as follows:
@ManyToOne
private Customer customer;
I cannot do this in Mongo (that's where I need help).
Now, to my question. I have two collections - Customer and Order. Both of them have CRUD APIs. How do I handle a ManyToOne relationship between Order and Customer.
If a user updates some properties of a Customer (name, email, etc), how does that change reflect in the Orders document?
I have the following options that come to my mind:
- When I update a customer, I can update all the order documents with the new customer details (this doesn't seem correct - might cause a lot of performance overhead, i feel)
- Using something like
@DbRef- if that's the case, can I get some links to related documents or references. - Came across a library called
RelMongothat allows you to use@ManyToOneannotations just like how you would in a relational world.
This could be a simple best-practices question, I'm not sure. However, any help goes a long way to improve my understanding!!
Thanks, Sriram