gpt4 book ai didi

javascript - 使用 TypeORM 使字段/列可选/必需

转载 作者:搜寻专家 更新时间:2023-11-01 00:19:52 31 4
gpt4 key购买 nike

我有这个成功写入 MySQL 的 cURL 命令:

curl -d '{"key1":"value", "key2":"value"}' -H "Content-Type: application/json" -X POST http://localhost:3010/customers

此查询能够通过 TypeORM 库写入数据库,如下所示:

import {Customer} from "../entity/customer";
import {getRepository} from "typeorm";
const RCustomer = getRepository(Customer);

router.post('/', (req, res, next) => {
return RCustomer.save(req.body).then(v => res.json({success: v}));
});

这本不应该发生,因为“key1”和“key2”不是客户表中的字段!

客户模型如下所示:

'use strict';

import {Entity, PrimaryGeneratedColumn, Column, Index} from "typeorm";
import {MooveBaseEntity} from "./base";

@Entity()
@Index(["email"], { unique: true })
export class Customer extends MooveBaseEntity {

@PrimaryGeneratedColumn()
id: number;

@Column()
firstName: string;

@Column()
lastName: string;

@Column()
email: string;

@Column()
phonePrimary: string;

@Column()
phoneSecondary: string;

}

所以我的想法是 - 我需要一种方法来使某些字段成为必填。理想情况下,默认情况下所有字段都是必需的,然后我可以设置一些可选字段(可为空或其他)。

我该怎么做?基本上,该 cURL 命令应该永远不会成功。

最佳答案

你有这样的行为是因为 save 不关心你发送给它的对象的属性,除了它需要的属性。在您的情况下,您没有发送 TypeORM 需要的任何属性,因此对于 typeorm,您的对象基本上是 {}save({}) 在您的情况下有效,因为您的所有列都不是必需的。要使它们成为必需的,您需要显式更改它们的可空状态,例如:

 @Column({ nullable: false })
firstName: string;

关于javascript - 使用 TypeORM 使字段/列可选/必需,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51131490/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com