Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM and MongoDB and Repositories: Cannot read property 'prototype' of undefined

I'm trying implement TypeORM with MongoDB using repositories. However, when I try to make use of repositories to manage the database, using the same structure as in this repository, things go a bit sideways. I'm getting the following error:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'prototype' of undefined

I have tried the following code:

import { Request, Response } from 'express';
import { getMongoRepository } from "typeorm";
import Task from "../models/Task";

export default class TasksController {
async listAll(request: Request, response: Response): Promise<Response> {
    const tasksRepository = getMongoRepository(Task);
    try {
      const tasks = await tasksRepository.find();
      return response.status(200).json({ "items": tasks });
    } catch (err) {
      return response.status(400).json({
        message: err.message,
      });
    }
  }
}

I know the error refers to implementing the .find() method. I have even managed to fetch the data, using a suggestion from this post replacing:

const tasks = await tasksRepository.find();

with

const tasks = await tasksRepository.createCursor(tasksRepository.find()).toArray();

but I still get the above mentioned error.

Anyone understands what's going on?

I have also managed to save data directly to the database through the use of the following script:

server.ts

import express from 'express';
import { createConnection } from 'typeorm'

const app = express();
const port = 3333;
createConnection();

app.use(express.json());

app.post('/tasks', (async (request, response) => {
  const { item } = request.body;
  task.item = item;

  const task = new Task();
  (await connection).mongoManager.save(task);

  return response.send(task);
}))

app.listen(port, () =>
  console.log(`Server running on port ${port}`)
);
like image 393
Rafael Avatar asked Dec 07 '22 09:12

Rafael


1 Answers

TypeORM is not support mongodb v4. https://github.com/nestjs/nest/issues/7798

You can use 3.7.0 instead.

like image 198
hiro Avatar answered Jan 19 '23 05:01

hiro