TypeORM FindById 不适用于 MongoDB
TypeORM FindById doesn't work with MongoDB
我正在尝试将 TypeORM 与 MongoDB 一起使用并进行表达,但我在使用基本内容时遇到了问题。
我刚刚为实体创建了一个具有基本 CRUD 操作的控制器。方法 save、findAll 和 find by Filter 工作正常,但我无法使需要 mongo id 的方法工作。
router.get("/", async(req: Request, res: Response) => {
const investmentRepository = getMongoRepository(Investment);
const investments = await investmentRepository.find();
res.send(investments);
});
router.get("/:id", async(req: Request, res: Response) => {
const investmentRepository = getMongoRepository(Investment);
const investment = await
investmentRepository.findOneById(req.params.id);
if (!investment) {
res.status(404);
res.end();
}
res.send(investment);
});
第二种方法总是返回404。
例如,这是一个在 get all "investment/"
上返回的实体
{
"id": "59dfd8cadcbd9d1720457008",
"name": "Teste LCI",
"startDate": 1466305200,
"numberOfDays": 365,
"type": "LCI_LCA"
}
如果我尝试为调用
的特定对象发送请求
investment/59dfd8cadcbd9d1720457008
响应总是 404。
delete 方法会发生相同的行为,引发异常
Cannot find entity to remove by a given id
我还尝试使用以下方法将字符串转换为 ObjectID:
new ObjectID(req.params.id);
但失败并显示错误 ObjectID 不是构造函数。
如果您收到错误 ObjectId 不是构造函数,那是因为您忘记在文件中要求它。您只需要:
const ObjectId = require('mongodb').ObjectId;
我正在尝试将 TypeORM 与 MongoDB 一起使用并进行表达,但我在使用基本内容时遇到了问题。
我刚刚为实体创建了一个具有基本 CRUD 操作的控制器。方法 save、findAll 和 find by Filter 工作正常,但我无法使需要 mongo id 的方法工作。
router.get("/", async(req: Request, res: Response) => {
const investmentRepository = getMongoRepository(Investment);
const investments = await investmentRepository.find();
res.send(investments);
});
router.get("/:id", async(req: Request, res: Response) => {
const investmentRepository = getMongoRepository(Investment);
const investment = await
investmentRepository.findOneById(req.params.id);
if (!investment) {
res.status(404);
res.end();
}
res.send(investment);
});
第二种方法总是返回404。 例如,这是一个在 get all "investment/"
上返回的实体{
"id": "59dfd8cadcbd9d1720457008",
"name": "Teste LCI",
"startDate": 1466305200,
"numberOfDays": 365,
"type": "LCI_LCA"
}
如果我尝试为调用
的特定对象发送请求investment/59dfd8cadcbd9d1720457008
响应总是 404。
delete 方法会发生相同的行为,引发异常
Cannot find entity to remove by a given id
我还尝试使用以下方法将字符串转换为 ObjectID:
new ObjectID(req.params.id);
但失败并显示错误 ObjectID 不是构造函数。
如果您收到错误 ObjectId 不是构造函数,那是因为您忘记在文件中要求它。您只需要:
const ObjectId = require('mongodb').ObjectId;