【问题标题】:Loopback POST array of entry?Loopback POST 条目数组?
【发布时间】:2020-10-01 02:06:16
【问题描述】:

我想针对 10 个查询插入 10 个条目,一个查询。

我读到可以通过发送这样的数组来做到这一点:

但我收到此错误:

我需要设置什么吗?我完全不知道该怎么办。

带有示例的回购:https://github.com/mathias22osterhagen22/loopback-array-post-sample

编辑: 人模型.ts:

import {Entity, model, property} from '@loopback/repository';

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

  @property({
    type: 'string',
    required: true,
  })
  name: string;


  constructor(data?: Partial<People>) {
    super(data);
  }
}

export interface PeopleRelations {
  // describe navigational properties here
}

export type PeopleWithRelations = People & PeopleRelations;

【问题讨论】:

  • 你还可以添加有问题的模型文件吗,我尝试添加数组来创建端点,它确实一次创建了多个条目。
  • 我刚刚编辑了我的帖子 + 我在项目中添加了一个 repo。您是如何设法“添加数组以创建端点”的?抱歉,我不确定我是否理解。
  • 我的意思是我在正文中传递了数组,正如您在示例中所展示的那样,它有效。
  • 您没有在模型文件中添加或更改任何内容?

标签: post loopbackjs loopback4


【解决方案1】:

您的代码的问题是:

"name": "ValidationError", "message": "People 实例不是 有效的。详情:0未在模型中定义(值:未定义); 1在模型中没有定义(值:未定义); name 不可能 空白(值:未定义)。",

在上面的 @requestBody 模式中,您正在申请插入单个对象属性,其中在您的正文中发送 [people] 对象的数组。

正如您在 people.model.ts 中看到的,您已声明属性名称是必需的,因此系统会查找属性“名称”,这显然在给定的对象数组中作为主节点不可用。

当您传递索引数组时,很明显的错误是您没有任何名为 0 或 1 的属性,因此会引发错误。

以下是您应该应用的代码帽,以插入多个类型的项目。

@post('/peoples', {
 responses: {
    '200': {
      description: 'People model instance',
      content: {
        'application/json': {
          schema: getModelSchemaRef(People)
        }
      },
    },
  },
})
async create(
  @requestBody({
    content: {
      'application/json': {
        schema: {
          type: 'array',
          items: getModelSchemaRef(People, {
            title: 'NewPeople',
            exclude: ['id'],
          }),
        }
      },
    },
  })
  people: [Omit<People, 'id'>]
): Promise<{}> {
  people.forEach(item => this.peopleRepository.create(item))
  return people;
}

你也可以在下面使用这个

Promise<People[]> {
  return await this.peopleRepository.createAll(people)
}

您可以通过修改请求正文来传递人员模型的数组。如果您需要更多帮助,可以发表评论。 我想你现在有一个明确的解决方案。 “快乐的环回:)”

【讨论】:

  • 仍然出现以下错误"The People instance is not valid. Details: 0 is not defined in the model (value: undefined); name can't be blank (value: undefined)."
  • @Madaky 我认为这只会改变界面上的“数组”
  • @RohitAmbre,您没有按照我的建议应用示例,现在更新完整代码。
  • @Madaky 运行良好,谢谢。我在 git 链接上打开的问题,然后是问题的链接:github.com/strongloop/loopback-next/issues/5716
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多