node.js 我如何定义 Sequelize.STRING 长度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16295118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:21:50  来源:igfitidea点击:

How do I define Sequelize.STRING length?

node.jspostgresqlstring-lengthsequelize.js

提问by gusera2334967

I want to define a length of a datatype in sequelize. There is my source code :

我想在 sequelize 中定义数据类型的长度。有我的源代码:

var Profile = sequelize.define('profile', {
  public_id: Sequelize.STRING,
  label: Sequelize.STRING
})

It create a table profiles with a public_id with a datatype varchar(255).

它使用数据类型为 varchar(255) 的 public_id 创建一个表配置文件。

I would like to define a public_id with varchar(32).

我想用 varchar(32) 定义一个 public_id。

I searched on the doc and the stack but couldn't find any answer...

我搜索了文档和堆栈,但找不到任何答案...

How can I do that please ?

请问我该怎么做?

回答by Szymon Wygnański

As it is mentioned in the documentation, use:

正如文档中提到的,使用:

Sequelize.STRING(32) 

回答by Chris Travers

First, I think you need to rethink your design just a little bit. The basic point is that length constraints should be meaningful, not just there to save space. PostgreSQL does not store 'A'::varchar(10) any differently than it does 'A'::text (both are stored as variable length text strings, only as long as the value stored, along with a length specifier and some other metadata), so you should use the longest size that can work for you, and use the lengths for substantive enforcement rather than to save space. When in doubt, don't constrain. When you need to make sure it fits on a mailing label, constrain appropriately.

首先,我认为您需要稍微重新考虑一下您的设计。基本点是长度限制应该是有意义的,而不仅仅是为了节省空间。PostgreSQL 存储 'A'::varchar(10) 与存储 'A'::text 没有任何不同(两者都存储为可变长度文本字符串,只要存储的值,以及长度说明符和其他一些元数据),因此您应该使用可以为您工作的最长大小,并将长度用于实质性执行而不是节省空间。有疑问时,不要拘束。当您需要确保它适合邮寄标签时,请适当限制。

Secondly Dankohn's answer above:

其次是上面丹科恩的回答:

var Profile = sequelize.define('PublicID', {
  public_id: {
  validate: { len: [0,32] })

is how you would then add such enforcement to the front-end. Again, such enforcement should be based on what you know you need, not just what seems like a good idea at the time, and while it is generally easier to relax constraints than tighten them, for string length, it's really a no-brainer to do things the other way.

是您如何将此类强制添加到前端的方式。同样,这种强制执行应该基于你知道你需要什么,而不仅仅是在当时看起来是个好主意,虽然放松约束通常比收紧约束更容易,但对于字符串长度,这真的很容易以另一种方式做事。

As for using such in other applications, you'd probably want to look up the constraint info in the system catalogs, which gets you into sort of advanced territory.

至于在其他应用程序中使用它,您可能希望在系统目录中查找约束信息,这会让您进入某种高级领域。