Typescript – 为什么“方法”属性不存在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。 但是对于打字稿,这是错误的。

接下来,我查找定义。 我find方法(名称:string,FN:function)和方法(方法:对象)这些属性,但它没有methods


总之,你不回答为什么mongoose定义的作者没有定义财产。 我需要一个答案mongoosemethods实际上是否可用?

没有在纯JavaScript中没有“方法”这样的属性。 它是mongoose的细节。 请注意,node.js在内部使用与Chrome浏览器相同的Google V8 JavaScript引擎 – 所以不存在像node.js的纯javascript。

methods属性确实存在于mongoose中,但是使用mongoose方法/静态方式就像打字稿中的javascript会导致错误。 以下是一些解决方法。

解决方法A:

 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); }) 
    Interesting Posts