我有以下架构:
const contentSchema = new Schema({
name: {
type: String,
required: true
},
type: {
type: String,
required: true
},
value: {
type: String,
required: true
}
});
const contentArraySchema = new Schema({
contentArray: [contentSchema]
});
const pageSchema = new Schema({
contents: [contentSchema]
});
我想将对象和数组混合添加到pageSchema中。如果我有一个数组,我想用contentSchema对象填充它,然后将其添加到pageSchema contents字段数组。如果没有数组,我只想将contentSchema对象添加到pageSchema内容字段数组中。
我只是要使用混合模式类型,但不确定执行此操作的最佳方法是什么,以及对基本数据库搜索将产生什么影响。
我还考虑过做类似在这篇帖子Here上看到的事情:
pageSchema.pre('validate', function (next) {
if (type === 'array') {
//use content array schema
} else {
//use regular content schema
}
next()
});
但是我不确定这是什么最佳实践。希望有人对此有一定的经验,可以为您提供帮助。谢谢。