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

使用Next.js搭配Mongoose调用模型函数触发TypeError致构建失败

解决Next.js 13构建时Mongoose模型静态方法/实例方法类型错误问题

问题原因

Next.js 13的pages/api在构建阶段会执行严格的类型校验,而Mongoose默认的models.User并不会自动关联你自定义的UserModel类型。开发阶段类型推断可能暂时掩盖问题,但构建时严格的类型检查会直接抛出“属性不存在”或“不可调用”的错误。

解决方案

方案1:显式指定导出模型的类型

修改模型文件的导出语句,通过类型断言强制告诉TypeScript导出的模型属于你定义的UserModel类型:

import { Model, Schema, models, model } from 'mongoose';
import { User } from 'types/user';

interface UserModel extends Model<User> {
    findAuthenticated(hash: string): Promise<User>;
    getProfile(): Promise<User>;
}

const userSchema = new Schema<User, UserModel>({/* 你的Schema定义 */});

// 给模型添加静态方法
userSchema.statics.findAuthenticated = async function(hash: string) {
  // 方法实现
};
userSchema.statics.getProfile = async function() {
  // 方法实现
};

// 显式断言类型
export default (models.User || model<User, UserModel>('User', userSchema)) as UserModel;

方案2:全局扩展Mongoose的Models接口

在项目的类型定义文件(比如types/mongoose.d.ts)中扩展Mongoose内置的Models接口,让TypeScript全局识别models.User的类型:

import { UserModel } from '../path/to/your/user/model/file';

declare module 'mongoose' {
  interface Models {
    User: UserModel;
  }
}

这种方式无需每次导出模型都做类型断言,全局生效。

方案3:确保模型初始化完成

在API路由中调用模型方法前,先确认模型已完成初始化:

// pages/api/user.ts
import UserModel from '../../models/User';

// 显式获取模型,确保初始化完成
const User = UserModel;

export default async function handler(req, res) {
  if (req.method === 'GET') {
    const user = await User.findAuthenticated('some-hash');
    res.status(200).json(user);
  }
}

验证

修改完成后重新执行next build,类型校验将通过,不会再抛出TypeError。

内容的提问来源于stack exchange,提问作者Hummel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 23:10:25