1

在环回 4 中,当我发布单个值时出现一个奇怪的问题,例如:

{
email: "sit@leoVivamusnibh.net",
password: "430975896"
}

在大摇大摆中,没有问题报告,但是当我发布一组值时,例如:

[{
email: "metus.facilisis.lorem@sitamet.org",
password: "168978823"
},
{
email: "fringilla@enim.org",
password: "933013104"
}]

该值已发布到数据库,但出现此错误:

{
  "error": {
    "statusCode": 500,
    "message": "Internal Server Error"
  }
}

并在控制台中显示以下几行:

POST /users 中未处理的错误:500 TypeError:model.toObject 不是 UserRepository.toEntity 中的函数(D:\apps\test\node_modules@loopback\repository\src\repositories\legacy-juggler-bridge.ts:471:39 ) 在 UserRepository.create (D:\apps\test\node_modules@loopback\repository\src\repositories\legacy-juggler-bridge.ts:338:17)

用户模型

@model({ settings: {} })
export class User extends Entity {
  @property({
    type: 'number',
    id: true,
    generated: true
  })
  id: number;

  @property({
    type: 'string'
  })
  email: string;

  @property({
    type: 'string'
  })
  password: string;
  constructor(data?: Partial<User>) {
    super(data);
  }
}

用户控制器

async create(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(User),
        },
      },
    })
    user: Omit<User, 'id'>,
  ): Promise<User> {
    return this.userRepository.create(user,
                                    //{ exclude: ['id'] }
                                      );
  }
4

2 回答 2

1

正如您所提到的,您在请求正文中请求的数组很好。

问题是,如果您想在数据库中创建这些用户配置文件,您将必须执行以下操作:

async create(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(User),
        },
      },
    })
    userList: User[],
  ): Promise<User> {
      return await Promise.all(
        userList.forEach(user => {
          return await this.userRepository.create(user);
       ))
  }

希望这会有所帮助,如果您有任何疑问或建议,请写信给我。谢谢

于 2019-10-18T15:34:53.287 回答
1

首先,在 LoopBack 4 中,该POST方法不接受要创建的模型实例数组,它仅适用于单个模型。

话虽如此,当请求包含对象数组时,LoopBack 不应响应 500 错误。我希望得到422 Unprocessable Entity回应。

请问能补个bug吗?https://github.com/strongloop/loopback-next/issues/new/choose

于 2019-10-04T15:19:43.293 回答