[英]Typescript - Why `methods` property doesn't exist in mongoose?
我在 nodejs 中編寫打字稿。 當我編寫 mongoose 模式時,Typescript 編譯器告訴我如下:
app/models/user.schema.ts(15,12): error TS2339: Property 'methods' does not exis
t on type 'Schema'.
我覺得很奇怪。 我在指南的Instance methods
部分參考了文檔。 它提到如下:
// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function (cb) {
return this.model('Animal').find({ type: this.type }, cb);
}
我認為methods
是一個可用的屬性或 API。 但是對於打字稿來說,這是錯誤的。
接下來,我查找定義。 我找到了method(name: string, fn: Function)和method(method: Object)這些屬性,但它沒有methods
。
簡而言之,您沒有回答我為什么 mongoose 定義的作者沒有定義該屬性。 我需要一個答案mongoose
的methods
實際上是否可用?
不,純 javascript 中沒有“方法”這樣的屬性。 它是貓鼬的特性。 請注意,node.js 在內部使用與 chrome 瀏覽器相同的 google V8 javascript 引擎 - 所以 node.js 沒有純 javascript 這樣的東西。
methods
屬性確實存在於 mongoose 中,但是像 typescript 中的 javascript 一樣使用 mongoose 方法/靜態會導致錯誤。 以下是一些解決方法。
解決方法一:
userSchema['methods'].findSimilarTypes = function (cb) {
return this.model('Animal').find({ type: this.type }, cb);
}
解決方法B:
userSchema.method('findSimilarTypes', function (cb) {
return this.model('Animal').find({ type: this.type }, cb);
})
今天 mongoose 發布了新版本的 mongoose 5.11.0 。 如果你在 package.json 中有 "mongoose": "^5.x.xx" 你會得到很多這樣的錯誤。 所以,我建議改變 "mongoose": "~5.x.xx" 來修復它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.