我是Web编程的新手,我看到很多关于创建一个好的API和创建一个好的网页的文章和帖子。 但是没有太多的文章涉及 api 和网页如何在 1 对多数据库模型中设置/获取引用方面进行交互。
我从以下模型开始:
用户
const UserSchema = new Schema({
email: {type: String, required: true},
password: {type: String, required: true},
})
地址
const AddressSchema = new Schema({
street: {type: String, required: true},
city: {type: String, required: true},
state: {type: String, required: true},
zip: {type: String, required: true},
})
我想使用引用和"填充"将这两个模型链接在一起。( https://mongoosejs.com/docs/populate.html ) 因为用户可能有许多地址(工作、家庭、账单、办公室、送货等)
我有一些问题
我应该在用户地址中保存引用数组:
const UserSchema = new Schema({
email: {type: String, required: true},
password: {type: String, required: true},
address: [{ type: Schema.Types.ObjectId, ref: 'Address' }]
})
或者我应该在用户地址中保留引用
const AddressSchema = new Schema({
street: {type: String, required: true},
city: {type: String, required: true},
state: {type: String, required: true},
zip: {type: String, required: true},
user: { type: Schema.Types.ObjectId, ref: 'User' }
})
接下来,我还假设一个好的 API 遵循单一责任原则 (https://en.wikipedia.org/wiki/Single_responsibility_principle),并且在调用时,API仅创建用户(或)地址,不执行其他任何操作。
通过做出该假设,我何时/何地以及如何在用户或地址中分配参考 ID?
何时何地调用"填充"方法以填充结果集?
我需要一些最佳实践建议和/或一个非常好的例子。
在这种情况下,条件为"一对多"意味着一个用户的地址不会超过 10 个,或者在最坏的情况下,让我们考虑 20 个。因此,将它们嵌入到一个文档中将最有效。
所以我建议你把两者都放在一个集合中。
const UserSchema = new Schema({
email: {type: String, required: true},
password: {type: String, required: true},
address: [{
street: {type: String, required: true},
city: {type: String, required: true},
state: {type: String, required: true},
zip: {type: String, required: true}
}]
})
如果您希望它在不同的集合中,那么最好在用户地址中保留引用,因为您在数据库中的第一件事将是用户集合,然后您将更新地址。