我有一个Comment
模型, comments 可以添加到Post
或其他Comment
.我希望定义一个指向Post
或Comment
型号的parentCollection
字段,然后定义对象的ID,而不是定义两个可选的parentPost
和parentComment
字段.我是Mongoose/MongoDB的新手.这是可能的吗?这种方法有什么警告吗?
// What I have
const commentSchema = new Schema({
parentComment: {type: Schema.Types.ObjectId, ref: 'Comment'},
parentPost: {type: Schema.Types.ObjectId, ref: 'Post'}
})
// What I want
const commentSchema = new Schema({
parentModel: {}, // Not sure what to put here, String maybe?
parentID: {type: Schema.Types.ObjectId} // Maybe ref could point to parentModel?
})
我的目标是减少具有许多可能的父类型的模型的字段数量.这在实践中曾经这样做过吗?或者第一种具有多个领域的方法是常见的方法吗?