定义时不调用函数
Function is not called when defined
我很确定我将实例方法定义为函数,但在调用标有 <--
的行时收到错误 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)
}
我认为您可能想在从中派生模型 class 之前尝试在模式上定义方法:
const productSchema = /* ... */;
productSchema.methods.toggleOnSale = function() {
this.onSale = !this.onSale;
return this.save();
}
const Product = mongoose.model('Product', productSchema)
我很确定我将实例方法定义为函数,但在调用标有 <--
的行时收到错误 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)
}
我认为您可能想在从中派生模型 class 之前尝试在模式上定义方法:
const productSchema = /* ... */;
productSchema.methods.toggleOnSale = function() {
this.onSale = !this.onSale;
return this.save();
}
const Product = mongoose.model('Product', productSchema)