gpt4 book ai didi

node.js - TypeError : this. 模型不是函数

转载 作者:太空宇宙 更新时间:2023-11-03 23:52:43 25 4
gpt4 key购买 nike

这是我的代码

var animalSchema = new Schema({ name: String, type: String });

animalSchema.methods.findSimilarTypes = (cb) => {
console.log(this)
return this.model("Animal").find({ type: this.type }, cb);
};

var Animal = model("Animal", animalSchema);
var dog = new Animal({ type: "dog" });

dog.findSimilarTypes((err, dogs) =>{
console.log(dogs);
});

当我这样写的时候函数(cb) {
return this.model('Animal').find({ type: this.type }, cb);
};
一切正常。但是当我使用箭头函数时,出现错误。

TypeError: this.model is not a function

这个问题可以解决吗?

最佳答案

这是因为箭头函数没有自己的this。它在词汇上绑定(bind)了它们的上下文。

由于您在箭头函数中使用了 this.model 并且它不是该文件/ Controller 的实例,因此 this 将指向窗口对象。这将导致错误:您的 this.model 不是函数。

希望能消除您的疑虑。

关于node.js - TypeError : this. 模型不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58748507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com