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

运行MEAN项目用户模型代码时出现TypeError错误求助

解决MEAN项目中mongoose.Schema未定义的TypeError错误

问题分析

你碰到的这个TypeError: Cannot read property 'Schema' of undefined错误,原因特别直接——你在尝试访问mongoose.Schema之前,还没加载mongoose模块。看你给出的代码:

const Schema = mongoose.Schema;
var mongoose = require("mongoose");

代码是从上到下执行的,当第一行试图读取mongoose.Schema时,mongoose变量还没被赋值(第二行才会加载模块),此时它是undefined,自然没法读取它的Schema属性,就抛出了这个错误。

修复方案

只需要调整代码的执行顺序,先加载mongoose模块,再去访问它的Schema属性即可:

方案1:基础修复(调整require顺序)

// 先加载mongoose模块
var mongoose = require("mongoose");
// 再从mongoose中获取Schema
const Schema = mongoose.Schema;

var UserSchema = new Schema({
  username: { type: String, lowercase: true, required: true, unique: true },
  email: { type: String, lowercase: true, required: true, unique: true },
  password: { type: String, required: true },
});

module.exports = mongoose.model("User", UserSchema);

方案2:ES6解构赋值(更简洁写法)

如果你习惯ES6语法,可以直接在加载模块时解构出Schema,既能避免顺序问题,代码也更简洁:

// 一次性加载mongoose并解构出Schema
const mongoose = require("mongoose");
const { Schema } = mongoose;

var UserSchema = new Schema({
  username: { type: String, lowercase: true, required: true, unique: true },
  email: { type: String, lowercase: true, required: true, unique: true },
  password: { type: String, required: true },
});

module.exports = mongoose.model("User", UserSchema);

额外提醒

  • 确认你已经在项目根目录执行过npm install mongoose安装了依赖,如果没装的话,先执行这个命令。
  • 后续使用mongoose的其他功能时,都要记住先加载模块,再访问模块的属性或方法,避免再出现类似的顺序错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:32:36