【问题标题】:TypeORM error with MongoDB: .find() does not work, error: TypeError: Cannot read property 'prototype' of undefinedMongoDB 的 TypeORM 错误:.find() 不起作用,错误:TypeError:无法读取未定义的属性“原型”
【发布时间】:2021-11-16 07:59:44
【问题描述】:

我按照here 的描述设置了一个 Nest.Js / TypeORM / MongoDB 堆栈。

使用create()函数在MongoDB中创建对象用户,对象被记录到正确的数据库到User集合中。

但是,当我尝试使用 find({id})findAll() 函数获取它时,我收到一个错误,即使它存在,我也无法从数据库中获取它。

这是我的user.service.ts 文件:

import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { MongoRepository } from 'typeorm';
import { validate } from 'class-validator';
import { CreateUserDto } from './user.dto';
import { User } from '../model/user.entity';
import { UserRO } from './user.interface';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: MongoRepository<User>,
  ) {}

  // abstracting access to the model via service
  public async getAll() {
    // getting data from database
    return await this.userRepository.find();
  }

  // abstracting access to the model via service
  public async get(id: string) {
    const user = await this.userRepository.findOne({ _id: id });
    if (!user) {
      const errors = { User: ' not found' };
      throw new HttpException({ errors }, 401);
    }

    return this.buildUserRO(user);
  }



  async create(dto: CreateUserDto): Promise<UserRO> {
    // check uniqueness of username/email
    const { username } = dto;
    const newUser = new User();
    newUser.username = username;
    // newUser.contexts = [];

    const errors = await validate(newUser);
    if (errors.length > 0) {
      const _errors = { username: 'Userinput is not valid.' };
      throw new HttpException(
        { message: 'Input data validation failed', _errors },
        HttpStatus.BAD_REQUEST,
      );
    } else {
      const savedUser = await this.userRepository.save(newUser);
      return this.buildUserRO(savedUser);
    }
  }


}

还有user.interface.ts:

export interface UserData {
  username: string;
  _id: string;
}

// user response object
export interface UserRO {
  user: UserData;
}

还有一部分user.controller.ts

  @Get(':id')
  findOne(@Param('id') id: string): Promise<UserRO> {
    console.log(`getting user with id: ${id}`);
    const user = this.serv.get(id);
    return user;
  }

最后是model/user.entity.ts:

@Entity({ name: 'User' })
export class User {
  @ObjectIdColumn()
  _id: string;

  @Column({ type: 'varchar', length: 50 })
  username: string;

  @OneToMany((type) => Context, (context) => context.user)
  contexts: Context[];
}

我尝试查找已保存的上下文时遇到的错误:

[Nest] 75671  - 09/22/2021, 9:22:18 PM   ERROR [ExceptionsHandler] Cannot read property 'prototype' of undefined
TypeError: Cannot read property 'prototype' of undefined
    at FindCursor.cursor.toArray (/Users/deemeetree/Documents/Root/benchmark-sql-graph/src/entity-manager/MongoEntityManager.ts:707:37)
    at MongoEntityManager.<anonymous> (/Users/deemeetree/Documents/Root/benchmark-sql-graph/src/entity-manager/MongoEntityManager.ts:190:46)
    at step (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:143:27)
    at Object.next (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:124:57)
    at fulfilled (/Users/deemeetree/Documents/Root/benchmark-sql-graph/node_modules/typeorm/node_modules/tslib/tslib.js:114:62)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

我尝试使用 MongoDB 4. 和 3. 版本,但问题相同。

我做错了什么以及如何通过此错误并能够在 MongoDB 中很好地查询记录?

谢谢!

【问题讨论】:

    标签: mongodb nestjs typeorm


    【解决方案1】:

    我解决了这个问题,将 mongodb 的版本从 4.1.2 降级到 3.7.1。您可以在此处找到更多详细信息:https://github.com/typeorm/typeorm/issues/8146

    【讨论】:

      【解决方案2】:

      这是版本问题。 要解决此问题,请尝试通过降级使用版本 3

      首先删除现有的mongodb包

      npm uninstall mongodb
      // Or
      yarn remove mongodb
      

      然后使用版本 3 再次安装。

      npm install mongodb@3
      // Or
      yarn add mongodb@3
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-07
        • 1970-01-01
        • 2017-05-05
        • 2019-04-05
        • 2020-09-03
        • 1970-01-01
        相关资源
        最近更新 更多