我有示例输入
-vvv
如何用猫鼬编写模型架构?
这是我的模式
[[1,2],[3,2],[1,3],...,[4,5]]
这不起作用。
输入应为具有fixedSize的数组,其长度为2,例如const SubproductSchema = new Schema({
...
positions: [{
type: [Number],
validate: {
validator: function(value){
return value.length == 2;
},
message: 'Positions should be 2'
}
}]
}, {
timestamps: true
});
如果输入为[[1,2],[3,2],[1,3],...,[4,5]]
,则应使用[[1,2,4],[3,2],[1,3],...,[4,5]]
进行验证
更新
我也尝试了这段代码(我猜在逻辑上是正确的):
'Position should be 2'
我的帖子是
const SubproductSchema = new Schema({
...
positions: {
type: [{
type: [Number],
validate: {
validator: function(value){
return value.length == 2;
},
message: 'Positions should be 2'
}
}],
}
}, {
timestamps: true
});
它输出错误:
子产品验证失败:职位:由于以下原因而无法投射到阵列 路径\“ positions \”“
上的值\” [[[2,3],[1,4],[4,5]] \“
答案 0 :(得分:1)
这就是你想要的...
const SubproductSchema = new Schema({
...
positions: [{
type: [Number],
validate: [limit, 'Positions should be 2']
}]
}, { timestamps: true });
const limit = (val) => {
let subElementsValidated = true;
val.forEach(el => {
if (el.length != 2){
subElementsValidated = false;
return;
}
});
return subElementsValidated;
}
答案 1 :(得分:0)
您可以像这样更改验证选项
const SubproductSchema = new Schema({
...
positions: [{
type: [Number],
validate: [limit, 'Positions should be 2']
}]
}, {
timestamps: true
});
const limit = (val) => {
return val.length == 2;
}