我很确定我将实例方法定义为一个函数,但是TypeError: foundProduct.toggleOnSale is not a function
在调用标有<--
. 我不明白为什么会这样。
const Product = mongoose.model('Product', productSchema)
productSchema.methods.toggleOnSale = function() {
this.onSale = !this.onSale;
return this.save();
}
const findProduct = async () => {
const foundProduct = await Product.findOne({ name: 'Mountain Bike' });
console.log(foundProduct)
await foundProduct.toggleOnSale() <--
console.log(foundProduct)
}
我认为您可能想在从中派生模型类之前尝试在模式上定义方法:
const productSchema = /* ... */;
productSchema.methods.toggleOnSale = function() {
this.onSale = !this.onSale;
return this.save();
}
const Product = mongoose.model('Product', productSchema)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句