MongoDB Embedded Objects 没有 ID(空值)
2022-09-01 10:19:25
我有一个关于MongoDB与Spring Data的问题。我有这些域类:
@Document
public class Deal {
@Id
private ObjectId _id;
private Location location;
private User user;
private String description;
private String title;
private String price;
private boolean approved;
private Date expirationDate;
private Date publishedDate;
}
@Document
public class Location {
@Id
private ObjectId _id;
private Double latitude;
private Double longitude;
private String country;
private String street;
private String zip;
}
@Document
public class User {
@Id
private ObjectId _id;
private String email;
private String password;
private String profile_image_url;
private Collection<Deal> deals = new ArrayList<Deal>();
}
有了这些域,我可以成功地进行 CRUD。只有一个问题。保存包含成交的用户时,成交和位置_id保存到 MongoDB 时设置为 null。为什么MongoDB不能为嵌入对象生成唯一的ID?
使用一笔交易保存用户后的结果:
{ "_id" : ObjectId( "4fed0591d17011868cf9c982" ),
"_class" : "User",
"email" : "milo@gmail.com",
"password" : "mimi",
"deals" : [
{ "_id" : null,
"location" : { "_id" : null,
"latitude" : 2.22,
"longitude" : 3.23445,
"country" : "Denmark",
"street" : "Denmark road 77",
"zip" : "2933" },
"description" : "The new Nexus 7 Tablet. A 7 inch tablet from Google.",
"title" : "Nexus 7",
"price" : "1300",
"approved" : false,
"expirationDate" : Date( 1343512800000 ),
"publishedDate" : Date( 1340933521374 ) } ] }
从结果中可以看出,交易和位置 ID 设置为 NULL。