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

NestJS中使用Mongoose连接MongoDB遇undefined错误求助

解决NestJS中Mongoose插件加载报错:First param to schema.plugin() must be a function, got "undefined"

问题场景

开发NestJS应用连接MongoDB时,按照官方文档配置Mongoose并使用mongoose-unique-validator等插件,模块代码及依赖配置如下,但始终报错:'First param to schema.plugin() must be a function, got "undefined"'

模块代码

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: `.env.${process.env.NODE_ENV}`,
    }),
    MongooseModule.forRootAsync({
      useFactory: async (configService: ConfigService) => ({
        uri: configService.get<string>('MONGO_URI'),
        autoIndex: true,
        useNewUrlParser: true,
        useUnifiedTopology: true,
        connectionFactory: (connection: MongooseConnection) => {
          // Global plugins
          connection.plugin(mongooseUniqueValidator);
          connection.plugin(mongoosePaginate);
          connection.plugin(mongooseToJson);
          return connection;
        },
      }),
      inject: [ConfigService],
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})

package.json依赖

"dependencies": {
    "@nestjs/common": "^9.0.0",
    "@nestjs/config": "^2.2.0",
    "@nestjs/core": "^9.0.0",
    "@nestjs/mapped-types": "*",
    "@nestjs/mongoose": "^9.1.1",
    "@nestjs/platform-express": "^9.0.0",
    "@nestjs/platform-socket.io": "^9.2.1",
    "@nestjs/websockets": "^9.2.1",
    "helmet": "^6.0.1",
    "mongoose": "^6.4.3",
    "mongoose-paginate-v2": "^1.7.1",
    "mongoose-unique-validator": "^2.0.3",
    "openai": "^3.1.0",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^7.2.0"
  },

解决建议

1. 检查插件导入是否正确

报错核心原因是传入connection.plugin()的插件不是函数(即变量为undefined),大概率是导入方式错误:
确认所有插件的导入语句符合包的导出规则,示例:

// 正确导入mongoose-unique-validator(默认导出)
import mongooseUniqueValidator from 'mongoose-unique-validator';
// 正确导入mongoose-paginate-v2(默认导出)
import mongoosePaginate from 'mongoose-paginate-v2';

2. 补充缺失的插件依赖

代码中使用了mongooseToJson但package.json未包含对应依赖,需先安装常用的适配包:

npm install @meanie/mongoose-to-json

然后正确导入:

import mongooseToJson from '@meanie/mongoose-to-json';

3. 验证版本兼容性并重新安装依赖

当前mongoose@6.4.3与已安装的插件版本兼容,但如果存在隐性冲突,可尝试重置依赖:

rm -rf node_modules package-lock.json
npm install

4. 切换到Schema级别注册插件(备选方案)

如果全局注册仍有问题,可改为在具体Schema中单独注册,示例:

import { Schema } from 'mongoose';
import mongooseUniqueValidator from 'mongoose-unique-validator';

const UserSchema = new Schema({
  email: { type: String, unique: true }
});
UserSchema.plugin(mongooseUniqueValidator);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:25:19