我正在使用貓鼬,每次嘗試使用我為架構創建的方法時,它都會拋出以下錯誤訊息:
UnhandledPromiseRejectionWarning: TypeError: findItem.updatePrice is not a function
模型定義和實體創建:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/shopApp')
.then(()=>{
console.log('Working!');
})
.catch(err=>{
console.log('Error');
console.log(err);
})
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
price: {
type: Number
}
})
const product = mongoose.model('product', productSchema);
const bike = new product({name:'MTB', price: 599});
productSchema.methods.updatePrice = function(newprice){
this.price = newprice;
return this.save();
}
const updatedPrice = async ()=>{
const findItem = await product.findOne({name:'MTB'});
await findItem.updatePrice(500);
}
updatedPrice();
uj5u.com熱心網友回復:
在該示例檔案創建它的一個實體之前限定實體方法。
productSchema.methods.updatePrice = function(newprice){
this.price = newprice;
return this.save();
}
const product = mongoose.model('product', productSchema);
const bike = new product({name:'MTB', price: 599});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314281.html
標籤:javascript 节点.js MongoDB 猫鼬 方法
上一篇:MongoDB多重/嵌套聚合
