Я почти уверен, что определяю метод экземпляра как функцию, но получаю сообщение об ошибке 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.info(foundProduct)
await foundProduct.toggleOnSale() <--
console.info(foundProduct)
}
🤔 А знаете ли вы, что...
Node.js поддерживает работу с WebSocket для двусторонней связи между клиентом и сервером.
Я думаю, вы можете попробовать определить методы в схеме, прежде чем извлекать из нее класс модели:
const productSchema = /* ... */;
productSchema.methods.toggleOnSale = function() {
this.onSale = !this.onSale;
return this.save();
}
const Product = mongoose.model('Product', productSchema)