【问题标题】:how to make fixed size arrays inside array mongoose schema如何在数组猫鼬模式中制作固定大小的数组
【发布时间】:2020-04-15 11:22:24
【问题描述】:

我有示例输入

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

我的帖子是

{
    ...
    "positions": [[2,3], [1,4], [4, 5]]
}

它输出错误:

子产品验证失败:职位:转换为数组失败 路径 \"positions\"" 处的值 \"[ [ [ 2, 3 ], [ 1, 4 ], [ 4, 5 ] ]\"


模型应该看起来像

【问题讨论】:

  • @GeorgeBailey 我想这不是我的问题...解决了不是我的问题...我也尝试过索引 2d 或 2dsphere .. 问题是当我用 [[1, 2],[3,2],[1,3],...,[4,5]] 是错误验证失败:位置:Cast to Array failed for value \"[ [ 2, 3 ], [ 1, 4 ], [ 5, 6 ]\" at path \"positions\... 我不知道为什么我不能验证内部数组

标签: javascript node.js mongoose mongoose-schema


【解决方案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;
}

【讨论】:

    【解决方案2】:

    您可以像这样更改验证选项

    const SubproductSchema = new Schema({
        ...
        positions: [{
            type: [Number],
            validate: [limit, 'Positions should be 2']
        }]
      }, {
        timestamps: true
    });
    
    
    const limit = (val) => {
        return val.length == 2;
    }
    

    【讨论】:

    • "子产品验证失败:位置:Cast to Array 的值 \"[ [ [ 2, 3 ], [ 1, 4 ], [ 4, 5 ] ]\" 在路径 \"positions\ "", ----> 错误
    猜你喜欢
    • 2022-11-02
    • 2020-01-02
    • 2021-06-23
    • 2017-04-22
    • 2023-03-04
    • 2019-03-21
    • 2015-05-15
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多