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

使用Mongoose查询MongoDB users集合返回空数组问题排查

Mongoose查询MongoDB返回空数组排查方案

我有一个名为photos-album的MongoDB数据库,里面有一个users集合且存在用户数据,但用Mongoose查询所有用户时返回空数组。连接字符串是从Mongo Compass复制的,没有报错,请问哪里出问题了?

Mongo Compass中的用户文档结构

_id: ObjectId(string);
name: string;
username: string;
email: string;

相关代码文件

users.schema.ts

import { Schema } from 'mongoose';

export const UserSchema = new Schema({
  name: { type: String, required: true },
  username: { type: String, required: true },
  email: { type: String, required: true },
});

users.interface.ts

export interface User {
  name: string;
  username: string;
  email: string;
}

users.module.ts

@Module({
  imports: [
    MongooseModule.forFeature([
      { name: 'User', schema: UserSchema, collection: 'users' },
    ]),
  ],
  controllers: [UsersController],
  providers: [UsersService],
})
export class UsersModule {}

app.module.ts

@Module({
  imports: [
    MongooseModule.forRoot(
      'mongodb+srv://<username>:<password>@photos-album.m6dqk.mongodb.net/?retryWrites=true&w=majority&appName=photos-album',
    ),
    UsersModule,
  ],
})
export class AppModule {}

users.service.ts

@Injectable()
export class UsersService {
  constructor(@InjectModel('User') private readonly userModel: Model<User>) {}

  async findAll(): Promise<User[]> {
    const users = await this.userModel.find().exec();
    console.log('users:', users);
    return users;
  }
}

排查方向与解决方案
  • 数据库未指定:当前连接字符串没有明确指向photos-album数据库,Mongoose默认会连接test库。修改连接字符串,在末尾添加数据库名:
    mongodb+srv://<username>:<password>@photos-album.m6dqk.mongodb.net/photos-album?retryWrites=true&w=majority&appName=photos-album
    
  • 集合名称大小写不匹配:MongoDB集合名称区分大小写,确认代码中collection: 'users'和实际集合名称完全一致(比如实际是Users则会匹配失败)。
  • Schema字段校验过滤:检查现有文档的字段是否与Schema完全匹配,比如是否存在字段名格式差异(如user_name和username),或者文档缺少Schema中标记为required的字段,导致Mongoose自动过滤掉不符合的文档。
  • 验证查询有效性:在Mongo Compass中执行db.users.find()确认数据存在,同时在代码中添加精确查询测试,比如this.userModel.find({name: '某已知用户名'}),验证是否能返回结果。
  • 确认连接目标库:在连接配置中添加日志,确认实际连接的数据库名称:
    MongooseModule.forRoot(
      'mongodb+srv://<username>:<password>@photos-album.m6dqk.mongodb.net/photos-album?retryWrites=true&w=majority&appName=photos-album',
      {
        connectionFactory: (connection) => {
          console.log('已连接数据库:', connection.db.databaseName);
          return connection;
        }
      }
    )
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 22:43:22