mongodb - 在 MongoDb 中,是子文档引用还是扩展
问题描述
使用猫鼬,您可以创建一个子文档,如下所示:
export const UserSchema = new Schema({
email: {
type: String,
unique: true,
required: "email is required.",
match: [/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, 'Please fill a valid email address']
},
firstName: {
type: String,
required: "firstName is required."
},
lastName: {
type: String,
required: "lastName is required."
},
dateOfBirth: {
type: Date,
required: "dateOfBirth is required."
},
roles: [{
role: String,
required: "role is required",
validate: isValidUserRole
}],
address: AddressSchema,
});
地址架构
export const AddressSchema = new Schema({
streetAddress: {
type: String
},
addressLine2: {
type: String
},
city: {
type: String
},
state: {
type: String
},
zipCode: {
type: String
},
country: {
type: String
}
});
每当我保存用户时,猫鼬会创建一个包含嵌套地址数据或用户和地址的新用户文档,然后在用户实例中引用该地址文档吗?
我将如何处理 2 个用户共享相同地址的情况?
谢谢!
解决方案
你可以通过mongo
shell 查询你的数据来发现这一点。
当文档包含嵌入文档(这与 shell 中的嵌套哈希无法区分)时,嵌入文档完全属于顶级文档,不能通过引用包含到另一个文档中。
推荐阅读
- ms-access - Crosstab query generates Run-Time error '13' Type mismatch
- swift - task.arguments 中的 Swift 参数
- java - JTable更改列顺序然后编辑单元格提升错误
- node.js - 将数据发送到节点视图而不会丢失表单数据
- .net - 我们可以将 SOAP 协议与传输层协议一起使用吗?
- excel - 在运行时获取数据
- java - Java JFrame不在窗口中画线
- php - 视图中未定义的变量错误异常
- android - RecyclerView 适配器从模型中获取字符串作为内存对象
- javascript - Moment JS 日期更改?