4

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

  • 1
    have a look at this https://stackoverflow.com/questions/44209827/best-way-to-save-2d-array-to-mongodb – Muhammad Usman Dec 24 '19 at 11:10
  • have a look at this https://docs.mongodb.com/manual/core/2d/ – Aikansh Mann Dec 24 '19 at 11:43
  • @GeorgeBailey I guess it's not my problem... There are solving of not my problem... I also tried with indexing 2d or 2dsphere.. Problem is when I save positions with [[1,2],[3,2],[1,3],...,[4,5]] is error validation failed: positions: Cast to Array failed for value \"[ [ 2, 3 ], [ 1, 4 ], [ 5, 6 ] ]\" at path \"positions\... I don't know why I can not validate inner arrays – Daniyar Changylov Dec 25 '19 at 12:35

2 Answers2

2

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;
}
Azamat Ahunjanov
  • 356
  • 2
  • 15
0

You can change the validate options like this

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


const limit = (val) => {
    return val.length == 2;
}
  • "Subproduct validation failed: positions: Cast to Array failed for value \"[ [ 2, 3 ], [ 1, 4 ], [ 4, 5 ] ]\" at path \"positions\"", ----> error – Daniyar Changylov Dec 25 '19 at 15:41