使用MongoDB在findOne中使用Loopback4可能存在错误

问题描述 投票:0回答:1

描述/重现步骤/功能提议

我只有2个模型测试和atest测试有(id,name,age)atest有(testId),它指的是来自测试模型的id

我只有一个控制器(atest)有2个ENDPOINTS得到'/ eltest'>哪个findOne由testId

return await this.atestRepository.findOne({where : {testId : "5ca358720916cec7fd29e875"}});

通过id获取'/ anothertest'> findOne

return await this.atestRepository.findOne({where : {id : "5ca3589e0916cec7fd29e87a"}});

当前行为

第一个效果很好 - 但第二个没有找到存在的记录

预期的行为

两者都应该工作并找到数据库中的存在记录

我试过的搜索和解决方案

在atest模型中将@model()更改为@model({settings:{strictObjectIDCoercion:true,},});像开关一样工作 - 它会损坏工作的ENDPOINT并修复损坏的ENDPOINT

请使用this repo重现该问题

node.js express loopback v4l2loopback
1个回答
0
投票

在这种情况下,您需要使用2个不同的存储库。看这里

return await this.atestRepository.findOne({where : {id : "5ca3589e0916cec7fd29e87a"}});

最新型号id列应对应于最新型号中的id字段。它永远不会是测试模型ID。我想你打算做的是

export class AtestController {
  constructor(
    @repository(AtestRepository)
    public atestRepository : AtestRepository,

    @repository(TestRepository)
    public testRepository : TestRepository,
  ) {}

  @get('/eltest', {
    responses: {
      '200': {
        description: 'Array of Atest model instances',
        content: {
          'application/json': {
            schema: {type: 'array', items: {'x-ts-type': Atest}},
          },
        },
      },
    },
  })
  async find() {
    return await this.atestRepository.findOne({where : {testId : "5ca358720916cec7fd29e875"}});
  }

  @get('/anothertest', {
    responses: {
      '200': {
        description: 'Array of Atest model instances',
        content: {
          'application/json': {
            schema: {type: 'array', items: {'x-ts-type': Atest}},
          },
        },
      },
    },
  })
  async findA() {
    return await this.testRepository.findOne({where : {id : "5ca3589e0916cec7fd29e87a"}});
  }
}

注意我在这里使用testRepository。这应该工作。希望能帮助到你。

还请更换

@model({ settings: { strictObjectIDCoercion: true, }, })

@model()
© www.soinside.com 2019 - 2024. All rights reserved.