Subdocuments(嵌入文档)可以在以下模式中指定:
var childSchema = new Schema({ name: 'string' });
var parentSchema = new Schema({
children: [childSchema]
});
但是如何在集合上指定setters并且当类型是嵌入式模式时要求数组不为空?此代码将抛出嵌入式架构不是有效类型的错误:
function someSetter = function(val) {
// Do something on set
return val;
};
var parentSchema = new Schema({
children: [{type: childSchema, set: someSetter, required: true}]
});
答案 0 :(得分:1)
一种解决方案是在Schema实例化之后设置setter。
parentSchema.path('children').set(someSetter);
答案 1 :(得分:1)
您可以这样做:
var parentSchema = new Schema({
children: [{type: {childSchema}, set: someSetter, required: true}]
});