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

Mongoose报错Cannot read properties of undefined reading ('users')求助

解决MongoDB Schema报错:Cannot read properties of undefined reading ("users")

问题根源

这个错误的核心是代码尝试访问mongoose.models.users时,mongoose.models是undefined——说明当前mongoose实例还没和数据库建立有效连接,或者模型加载时机不对,导致模型无法正常注册。

分步解决方案

1. 修正数据库连接代码的错误

你的连接API里有两个明显问题,会直接导致连接失败:

  • 环境变量引用缺失process.env前缀
  • 抛出错误时使用了未定义的error变量

修正后的连接代码:

import mongoose from "mongoose";
// 正确读取环境变量
const MONGODB_URL = process.env.NEXT_MONGO_URL;

if (!MONGODB_URL) {
  // 抛出明确的错误提示
  throw new Error('MONGODB_URL环境变量未配置,请检查.env文件');
}

let cached = global.mongoose;
if (!cached) {
  cached = global.mongoose = {
    conn: null,
    promise: null,
  };
}

async function dbConnect() {
  if (cached.conn) {
    return cached.conn;
  }
  if (!cached.promise) {
    const opts = {
      bufferCommands: false,
    };

    cached.promise = mongoose.connect(MONGODB_URL, opts).then((mongoose) => {
      return mongoose;
    });
  }
  cached.conn = await cached.promise;
  return cached.conn;
}
export default dbConnect;

2. 统一模型文件的mongoose导入方式

你在用户模型里用了require('mongoose'),而连接API用的是import——在Next.js这类框架中,混用两种导入方式会创建多个mongoose实例,未连接的实例会导致模型注册失败。

修正后的用户模型代码:

// 改用import和连接API保持一致
import mongoose from "mongoose";

const userSchema = new mongoose.Schema(
  {
    firstName: { type: String, required: true, maxlength: 256 },
    lastName: { type: String, required: true, maxlength: 256 },
    username: {
      type: String,
      lowercase: true,
      unique: true,
      required: [true, "can't be blank"],
      match: [/^[a-zA-Z0-9]+$/, "is invalid"],
      index: true,
    },
    password: { type: String, required: true, maxlength: 256 },
    age: { type: Number },
    email: {
      type: String,
      lowercase: true,
      unique: true,
      required: [true, "can't be blank"],
      match: [/\S+@\S+\.\S+/, "is invalid"],
      index: true,
    },
  },
  // 注意这里是复数timestamps,单数不会生成自动时间戳
  { timestamps: true }
);

// 改用更稳妥的模型注册方式,避免直接访问mongoose.models导致undefined
let Users;
try {
  // 先尝试获取已注册的模型
  Users = mongoose.model('users');
} catch (error) {
  // 模型未注册时再创建
  Users = mongoose.model('users', userSchema);
}

export default Users;

3. 确保使用模型前先建立连接

在API路由或业务代码中,必须先调用dbConnect()并等待连接完成,再使用Users模型。示例:

import dbConnect from '../../lib/dbConnect';
import Users from '../../models/Users';

export default async function handler(req, res) {
  // 先等数据库连接建立
  await dbConnect();

  // 再执行模型操作
  if (req.method === 'GET') {
    try {
      const users = await Users.find({});
      res.status(200).json(users);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  }
}

验证步骤

  1. 检查.env文件,确认NEXT_MONGO_URL变量配置了正确的MongoDB连接字符串
  2. 重启Next.js开发服务器,确保代码修改生效
  3. 测试用户相关API接口,确认错误消失

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:50:36