You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 07:06:02