TypeORM FindById 不适用于 MongoDB

Fel*_*nsi 5 mongodb express typeorm

我正在尝试将 TypeORM 与 MongoDB 和 express 一起使用,但我在基本内容方面遇到了问题。

我刚刚为实体创建了一个具有基本 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);
});
Run Code Online (Sandbox Code Playgroud)

第二种方法总是返回 404。例如,这是在 get all "investment/" 时返回的实体

{
    "id": "59dfd8cadcbd9d1720457008",
    "name": "Teste LCI",
    "startDate": 1466305200,
    "numberOfDays": 365,
    "type": "LCI_LCA"
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试发送此特定对象调用的请求

投资/59dfd8cadcbd9d1720457008

响应始终是 404。

delete 方法发生相同的行为,引发异常

找不到要按给定 ID 删除的实体

我还尝试使用以下方法将字符串转换为 ObjectID:

new ObjectID(req.params.id);
Run Code Online (Sandbox Code Playgroud)

但它失败了错误 ObjectID is not a constructor。

J L*_*ood 7

如果您收到错误 ObjectId is not a constructor,那是因为您忘记在文件中要求它。所有你需要的是:

const ObjectId = require('mongodb').ObjectId;
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我可以让它工作导入 mongodb。`import * as mongodb from "mongodb";` `new mongodb.ObjectId(req.params.id);` 我不知道为什么 typeorm 包中的 ObjectID 不起作用。 (3认同)