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

使用Typegoose替代Mongoose后无法获取数据库查询结果的问题求助

Typegoose替代Mongoose后无法获取数据库查询结果的问题求助

大家好,我最近在把项目里的Mongoose原生Schema迁移到Typegoose的类式定义,遇到了一个棘手的问题:相同的服务器配置和数据库连接下,用Mongoose原生模型能正常查询到数据,但换成Typegoose生成的模型就返回空数组或者null。我反复核对了Typegoose的文档,配置看起来都是标准的,但就是找不到问题根源。先把我的相关代码和配置贴出来,麻烦各位帮忙看看!

技术栈

  • NodeJS 24
  • Express 5
  • TypeScript 5.8
  • Mongoose 8.16
  • @typegoose/typegoose 12.17

User模型的两种实现

import { prop, getModelForClass, Ref } from '@typegoose/typegoose';
import { Schema, model } from 'mongoose';

export interface IUser {
  userEmail: string;
}

// Mongoose原生实现(能正常查询)
const userSchema = new Schema<IUser>(
  {
    userEmail: {
      type: String,
      required: [true, 'msg1'],
      maxLength: [90, 'msg2'],
      unique: [true, 'msg3'],
    },
  },
  { timestamps: true },
);
export const MongooseUserModel = model<IUser>('User', userSchema);

// Typegoose实现(查询不到数据)
class UserSchema {
  @prop({ index: true, unique: true })
  public userEmail: string;
}
const TypegooseUserModel = getModelForClass(UserSchema);
export default TypegooseUserModel;

测试查询代码

import User from '@/models/user';

const simpleReqFn = async (req: Request, res: Response): Promise<void> => {
  // Mongoose模型返回:{ _id: new ObjectId('5eb8e1bc060bbf1653aa2106') }
  // Typegoose模型返回:null
  const userExists = await User.exists({ userEmail: 'email@aa.aa' });
  console.log('userExists: ', userExists);

  // Mongoose模型返回:包含5条数据的数组
  // Typegoose模型返回:空数组 []
  const users = await User.find({}).limit(5);
};

tsconfig配置

{
  "compilerOptions": {
    "target": "ES6",
    "module": "CommonJS",
    "rootDir": "src",
    "baseUrl": "./",
    "outDir": "dist",
    "removeComments": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "paths": {
      "@/*": ["src/*"]
    },
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "strictNullChecks": false
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

我自己排查过的点

  1. 数据库连接确认正常(Mongoose能查到数据,说明连接没问题)
  2. TypeScript的装饰器配置已经开启(tsconfig里的experimentalDecorators和emitDecoratorMetadata都设为true了)
  3. 字段的查询条件完全一致,没有拼写错误

补充一个可能的关键原因(刚想到的)

哦对了,突然意识到一个很容易踩的坑:集合名称不匹配!

你的Mongoose原生模型是model<IUser>('User', userSchema),Mongoose默认会把模型名转成小写复数作为集合名,也就是users(如果没有手动指定collection选项的话)。而Typegoose的getModelForClass(UserSchema)默认会用类名UserSchema的小写复数作为集合名,也就是userschemas——这显然和你数据库里实际的集合名不匹配,自然查不到数据!

解决方法:给Typegoose模型指定正确的集合名

修改Typegoose的模型代码,用@modelOptions装饰器指定集合名和timestamps(和Mongoose保持一致):

import { prop, getModelForClass, modelOptions } from '@typegoose/typegoose';

@modelOptions({ schemaOptions: { collection: 'users', timestamps: true } })
class UserSchema {
  @prop({ index: true, unique: true })
  public userEmail: string;
}

const TypegooseUserModel = getModelForClass(UserSchema);
export default TypegooseUserModel;

这样Typegoose生成的模型就会使用和Mongoose一样的users集合,应该就能正常查到数据了!

如果这个方法解决不了问题,我再提供更多项目配置文件~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 11:48:09