Mat*_*gen 2 post loopbackjs loopback4
我想用一个查询针对 10 个查询插入 10 个条目。
我需要设置一些东西吗?我根本不知道该怎么办。
带有示例的仓库:https://github.com/mathias22osterhagen22/loopback-array-post-sample
编辑:people-model.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;
Run Code Online (Sandbox Code Playgroud)
您的代码的问题是:
"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;
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用下面这个
Promise<People[]> {
return await this.peopleRepository.createAll(people)
}
Run Code Online (Sandbox Code Playgroud)
您可以通过修改请求正文来传递人员模型的数组。如果您需要更多帮助,您可以发表评论。我想你现在有一个明确的解决方案了。“快乐环回:)”