1

I met a strange question when I save position points in mongo by mongoose.

const testSchema1 = new mongoose.Schema({
  releasePoints: [{
    type: [Number]
  }]
}, {
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
});

const testSchema2 = new mongoose.Schema({
  releasePoints: [[Number]]
}, {
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
});

When I use testSchema2 save data success, but I use testSchema1 throw err:

validation failed: releasePoints: Cast to Array failed for value "[ [ 2.3635503,....

What difference about testSchema1 and testSchema2?

Can add validate in testSchema1?

For example:

const testSchema1 = new mongoose.Schema({
  releasePoints: [{
    type: [Number],
    validate: (val) => val.length === 2
  }]
}, {
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
});

  • I don't understand what you're searching for exactly. Do you want to add a validation to your schema to verify the array length ? Do you need to solve the cast error ? Or do you need to create a schema to have an array of longitudes and latitudes ? – Nathan Schwarz Feb 12 '19 at 12:48
  • could you also add the insert query you make with your example ? – Nathan Schwarz Feb 12 '19 at 13:04

1 Answers1

0

from https://mongoosejs.com/docs/schematypes.html#arrays you could argue that the first schema is a document array, and the 2nd one a primitive array.

from this thread How to define object in array in Mongoose schema correctly with 2d geo index, I would say that to make the first schema to behave like the 2nd one you should write it with releasePoints like so :

 releasePoints: [{
    type: Array , default: []
  }]

then add a validator to check for "Number type insertion". or something like:

releasePoints: [{
   data: [Number]
}]

But then you should access the value with the data attribute [x].data[y]

If you need to save a latitude/longitude value, you could simply do :

releasePoints: [{
   lat: Number,
   long: Number
}]
Nathan Schwarz
  • 631
  • 5
  • 19