javascript - 如何在数组 Mongoose 模式中创建固定大小的数组

标签 javascript node.js mongoose mongoose-schema

我有示例输入

[[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\""


模型应该看起来像 enter image description here

最佳答案

这就是您正在寻找的...

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/

相关文章:

javascript - Cordova:卡在 createbanner() 上的 AdModPro 插件

javascript - React Native x OneSignal 不显示通知

javascript - ng-mouseover 不显示数据

javascript - 在 templateUrl 覆盖它之前检索 AngularJS 指令的内部 HTML

javascript - 在 node.js 中使用 Gigya API

node.js - 亚马逊 MWS SubmitFeed Content-MD5 HTTP header 与亚马逊计算的 Content-MD5 不匹配

javascript - 使用 mongoose 查询测试快速路由

javascript - 将 JSON 中的空列表与空列表进行比较

node.js - 自定义错误未在 throw 语句或 next() 调用上正确传播

node.js - 如何更新 Mongoose 中的部分但非全部字段