我可以避免为某些字段添加 mongoDB 空值吗?

Can I avoid to add in mongoDB null value for some field?

我正在尝试用 MongoDB 开发一个 Spring 启动,我的问题是我不希望用户将数据库 emptynull 某些字段的值。

我已经尝试过我在网上找到的选项,但没有用。

代码:

@Data
@Entity
@Document(collection = "product")
public class Product {
    @Id
    private String id;

    @NotEmpty
    private String name;

    @NotNull(message = "brand must not be null")
    private String brand;

    @NotNull(message = "barCode must not be null")
    private String barCode;

    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    private LocalDate importDate;

    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    private LocalDate expireDate;

    @NotNull(message = "price must not be null")
    private Double price;

    private Double deal;

    @NotNull(message = "the quantity must not be null")
    private Integer quantity;
}

您正在使用

@NotNull

用于验证模型。

要省略将 null 值存储到 DB,您应该使用:

@Column(nullable=false)
private String brand;

更新:

看起来您的架构已经生成。
您没有共享项目的数据库配置。

如果您正在使用 Spring 启动,您必须设置 application.properties 附加属性以使其工作:

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.check_nullability=true

但是,不存储 null 值会有所帮助。

为防止存储空值,您应该为字符串字段添加:

@Size(min=1)

如果您想验证 IntegerDouble 它们的值大于 0,请使用 @Min:

@Min(value = 1L, message = "The price must be positive")
private Double price;