我正在尝试使用存储库在 MongoDB 中实现 TypeORM。但是,当我尝试使用存储库来管理数据库时,使用与 this repository 中相同的结构,事情有点偏了。我收到以下错误:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'prototype' of undefined
我尝试了以下代码:
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,
});
}
}
}
我知道错误是指实现 .find()
方法。我什至设法获取数据,使用来自 this post 的建议替换:const tasks = await tasksRepository.find();
和const tasks = await tasksRepository.createCursor(tasksRepository.find()).toArray();
但我仍然收到上述错误。有谁明白这是怎么回事?
我还设法通过使用以下脚本将数据直接保存到数据库中:
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}`)
);
最佳答案
TypeORM 不支持 mongodb v4。
https://github.com/nestjs/nest/issues/7798
您可以改用 3.7.0。
关于node.js - TypeORM 和 MongoDB 和存储库 : Cannot read property 'prototype' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68908467/