Mongoose调用自定义schema方法提示is not a function报错如何解决
错误原因
你调用自定义schema方法报错的核心问题是方法挂载的顺序错误:
Mongoose 会在调用mongoose.model()时基于传入的schema编译生成模型,编译完成后再给schema追加实例方法、静态方法等配置,不会同步到已经生成的模型上。你代码中先完成了product模型的编译,之后才给productSchema挂载updatePrice方法,导致所有product模型返回的实例都不包含这个方法,调用时就会抛出is not a function的错误。
修复方案
调整代码顺序,把所有schema的配置操作(包括自定义方法、中间件、虚拟属性等)都放在mongoose.model()调用之前:
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 } }) // 先挂载自定义方法,再编译模型 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}); const updatedPrice = async ()=>{ const findItem = await product.findOne({name:'MTB'}); await findItem.updatePrice(500); } updatedPrice();
内容的提问来源于stack exchange,提问作者Okta25
相关产品推荐
相关产品推荐

