post - Loopback POST 条目数组?
问题描述
我想针对 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;
解决方案
您的代码的问题是:
"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)
}
您可以通过修改请求正文来传递人员模型的数组。如果您需要更多帮助,可以发表评论。我想你现在有一个明确的解决方案。“快乐环回:)”