【发布时间】:2019-12-08 21:17:48
【问题描述】:
作为前端开发人员,我想为两个 mongoose 模型创建一些 isomorphic 对象。
假设我有一个用户个人资料:
const profileSchema = new Schema({
firstName: { type: String },
lastName: { type: String },
// example of difference between model schemas
__user: { type: ObjectId, ref: 'Users' },
}
我想创建一个Contact 列表,其中每个联系人都有一些相同的键:
const contactSchema = new Schema({
firstName: { type: String },
lastName: { type: String },
__profile: {
type: ObjectId,
ref: 'Profiles',
unique: true,
},
comment: { type: String },
}
注意: Contact 可能是两者:
- 作为
Profile的参考 - 并作为独立记录在 DB /
document。
===============================
我的问题:以这种方式组织模型是最好的方法,所以
- 联系人可能是对个人资料的引用
- 当类似
Profile键,如firstName将更新时,联系人firstName也会更新
避免下一个参考
await Contact.findById(SOME_ID).populate('__profile');
// result
{
firstName: '',
lastName: '',
__profile: {
firstName: 'Chuck',
lastName: 'Norris',
}
}
期望的结果 - 保持联系“同构”,例如:
{
firstName: 'Chuck', // the key value from profile
lastName: 'Norris', // the key value from profile
__profile: SOME_PROFILE_ID,
}
这可能吗?
P.S:在我的应用程序中,我使用 refs 并开始使用 discriminators 方法。
【问题讨论】:
标签: mongodb mongoose mongoose-schema mongoose-populate