Search code examples
javascriptnode.jsmongoosemongoose-schema

how to make fixed size arrays inside array mongoose schema


I have example input

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

How to write model schema in mongoose?
This is my Schema

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

And this does not work.
Input should be array with fixedSize with 2 length in array like this [[1,2],[3,2],[1,3],...,[4,5]]
If input is [[1,2,4],[3,2],[1,3],...,[4,5]], it should validate with 'Position should be 2'
UPDATED
I also tried this code (logically correct I guess):

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

And my post is

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

And it output error:

Subproduct validation failed: positions: Cast to Array failed for value \"[ [ 2, 3 ], [ 1, 4 ], [ 4, 5 ] ]\" at path \"positions\""


model should look like enter image description here


Solution

  • This is what you were looking...

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