我有示例输入
[[1,2],[3,2],[1,3],...,[4,5]]
如何在 Mongoose 中编写模型架构?
这是我的架构
const SubproductSchema = new Schema({
...
positions: [{
type: [Number],
validate: {
validator: function(value){
return value.length == 2;
},
message: 'Positions should be 2'
}
}]
}, {
timestamps: true
});
这不起作用。
输入应该是固定大小的数组,数组中长度为 2 [[1,2],[3,2],[1,3],...,[4,5]]
< br/>
如果输入为 [[1,2,4],[3,2],[1,3],...,[4,5]]
,则应使用 ' 进行验证位置应为 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]]
}
它输出错误:
Subproduct validation failed: positions: Cast to Array failed for value \"[ [ 2, 3 ], [ 1, 4 ], [ 4, 5 ] ]\" at path \"positions\""
最佳答案
这就是您正在寻找的...
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;
}
关于javascript - 如何在数组 Mongoose 模式中创建固定大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59467713/