定义时不调用函数

萨尔

我很确定我将实例方法定义为一个函数,但是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)
}
AKX

我认为您可能想在从中派生模型类之前尝试在模式上定义方法:

const productSchema = /* ... */;

productSchema.methods.toggleOnSale = function() {
    this.onSale = !this.onSale;
    return this.save();
}

const Product = mongoose.model('Product', productSchema)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章