I am pretty sure I am defining the instance method as a function but am getting the error TypeError: foundProduct.toggleOnSale is not a function
when calling the line marked with <--
. I don't understand why this is happening.
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)
}
CodePudding user response:
I think you might want to try defining the methods on the schema before deriving the model class out of it:
const productSchema = /* ... */;
productSchema.methods.toggleOnSale = function() {
this.onSale = !this.onSale;
return this.save();
}
const Product = mongoose.model('Product', productSchema)