猫鼬方法不是函数
Mongose method is not a function
我正在使用猫鼬,每次我尝试使用我为模式创建的方法时,它都会抛出以下错误消息:
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();
docs 中的示例在创建实例之前定义了实例方法。
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});
我正在使用猫鼬,每次我尝试使用我为模式创建的方法时,它都会抛出以下错误消息:
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();
docs 中的示例在创建实例之前定义了实例方法。
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});