在 GeoJSON 多邊形(或更嚴格地說:LinearRing)中,最后一組坐標需要評估為與第一組相同的值:
[[0,0], [0,1], [1,1], [1,0]] // bad
[[0,0], [0,1], [1,1], [1,0], [0,0]] // good
在使用 Mongoose 將 GeoJSON 多邊形保存到我的 MongoDB 實體時,我想做一些寬松的驗證(即修復物件,而不是拒絕它)。
我這樣做:
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; // I find this assignment everywhere in documentation, but it seems to fail
if (pol?.coordinates?.length > 1 && pol.coordinates[0] !== pol.coordinates[pol.coordinates.length - 1]) {
pol.coordinates.push(pol.coordinates[0]);
}
next();
});
tsc抱怨this總是未定義,pol除錯時物件確實未定義。但是,this根據 Visual Studio 除錯器,情況并非如此。

是否可以在預保存掛鉤期間修改物件,還是我需要事先這樣做?
注意,以防萬一:多邊形將始終是我的 MongoDB 實體中的子檔案:它被保存為另一個物件的形狀。
uj5u.com熱心網友回復:
如果您將箭頭函式而不是傳統函式傳遞給該函式,則該pre('save', ...)函式不會讓您訪問檔案。箭頭函式沒有this系結,而是使用父范圍。
來自Mozilla 開發檔案
箭頭函式沒有自己的 this、arguments 或 super 系結,不應該用作方法。
將箭頭更改為傳統的函式定義
從
polygonSchema.pre('save', {document: true, query: true}, async (next, opts) => {...}
到
polygonSchema.pre('save', {document: true, query: true}, async function (next, opts) {...}
uj5u.com熱心網友回復:
原來這是一個我沒想到的問題。顯然,您無法訪問this匿名(箭頭)函式中的物件(來源:https ://youtu.be/DZBGEVgL2eE?t=1495 )。我不知道這是否意味著一般的 JavaScript 或 Mongoose,特別是,但通過這樣做解決了問題:
const polygonSchema = new mongoose.Schema(PolygonSchema, { typeKey: '$type' }).loadClass(Polygon);
async function preSave() {
// @ts-ignore
const pol: Polygon = this;
if (pol?.coordinates?.length && pol.coordinates[0] !== pol.coordinates[pol.coordinates.length - 1]) {
pol.coordinates.push(pol.coordinates[0]);
}
}
polygonSchema.pre('save', preSave);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/478712.html
