When working with a GeoJSON Polygon (or more precisely, a LinearRing), it is crucial that the last set of coordinates matches the first one:
[[0,0], [0,1], [1,1], [1,0]] // incorrect
[[0,0], [0,1], [1,1], [1,0], [0,0]] // correct
For my MongoDB instance using Mongoose, I want to implement a lenient validation approach (fixing the object instead of rejecting it) when saving a GeoJSON Polygon.
Here is my approach:
export type Coordinates = number[]
// model object
export class Polygon {
type: string;
coordinates?: Coordinates[];
constructor(coordinates?: Coordinates[]) {
this.type = "Polygon";
this.coordinates = coordinates;
}
}
// schema object
export const PolygonSchema = {
type: String,
coordinates: [[Number]],
};
// model-schema binding
const polygonSchema = new mongoose.Schema(PolygonSchema, { typeKey: '$type' }).loadClass(Polygon);
// pre-save hook
polygonSchema.pre('save', async (next, opts) => {
// @ts-ignore
const pol: Polygon = this; // Struggling with this assignment
if (pol?.coordinates?.length > 1 && pol.coordinates[0] !== pol.coordinates[pol.coordinates.length - 1]) {
pol.coordinates.push(pol.coordinates[0]);
}
next();
});
When debugging, tsc
raises an error stating that this
is always undefined, even though the Visual Studio debugger shows otherwise.
Is it possible to modify the object during the pre-save hook, or should I handle this task beforehand?
In case it matters, a Polygon will always be a subdocument in my MongoDB instance, representing the shape of another object.