如何在数组猫鼬模式中制作固定大小的数组

how to make fixed size arrays inside array mongoose schema

我有示例输入

[[1,2],[3,2],[1,3],...,[4,5]]

如何在猫鼬中编写模型架构?
这是我的架构

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]]
如果输入为 [[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
});

而我的 post 是

{
    ...
    "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) => {
    return val.length == 2;
}

这就是您想要的...

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;
}