waterline-model.create - 主键

时间:2015-04-09 08:11:21

标签: database node.js sails.js waterline

我的主键ID为

attributes: {
   id: {
      type: 'integer',
      autoIncrement: true,
      primaryKey: true,
      unique: true
   },
    name: {
      type: 'string',
      unique: true,
      required: true
   },
}

我正在创建如下模型:

var model = {
     id: undefined,
     name: 'name',
};

waterlinemodel.create(model).exec(function(error,result){});

但是它会抛出错误: 错误(E_UNKNOWN)遇到意外错误]详细信息:错误:列“id”中的空值违反非空约束

因为'id'是主键,水线不应该看'id'属性的值是什么。

如何解决此错误?我不想删除'id',因为我已经为模型创建了值对象,它包含了model的所有属性。我正在设置我需要的值对象属性。我不需要为创建设置id属性。

3 个答案:

答案 0 :(得分:1)

我遇到完全相同的问题,尤其是配置为使用postgresql的模型。将其设置为磁盘或内存时,将创建资源,但使用postgresql时,不会使用非空约束错误创建资源。

无论我是否设置autoPK: true,都不会设置ID。即使使用autoPK:false在模型上设置id属性也不起作用。

答案 1 :(得分:0)

正如文件所说:

Will set the primary key of the record. This should be used when autoPK is set to false.

attributes: {
  uuid: {
    type: 'string',
    primaryKey: true,
    required: true
  }
}

您需要在模型上设置autoPK : false

doc:https://github.com/balderdashy/waterline-docs/blob/master/models.md#primarykey

的链接

答案 2 :(得分:0)

2019答​​案

jaumard的文档链接现在出现404错误,但我认为自2015年以来情况可能有所改变...

Sails.js具有在config/models.js中定义的基本属性,在新生成的项目中看起来像这样:

attributes: {
  createdAt: { type: 'number', autoCreatedAt: true, },
  updatedAt: { type: 'number', autoUpdatedAt: true, },
  id: { type: 'number', autoIncrement: true, },
}

另外,默认的primaryKey设置为id。如果要覆盖它,则需要在完整的模型定义中明确指定新的primaryKey。例如,如果您想将name用作primaryKey,则可以使用以下方式:

module.exports = {
  primaryKey: 'name',
  attributes: {
    name: {
      type: 'string',
      unique: true,
      required: true
    },
    // ...
  },
}

通知,我将primaryKey放在attributes外面。这个很重要。您的primaryKey也将需要uniquerequired约束。

此外,如果要禁用id列以使其不提交给数据库,则必须将id替换为值false,但是必须定义不同的primaryKey,否则在启动应用程序时会出现错误。问题中显示的错误可能与以下事实直接相关:模型将id明确定义为undefined。如何禁用id的示例如下所示:

module.exports = {
  primaryKey: 'name',
  attributes: {
    id: false,
    name: {
      type: 'string',
      unique: true,
      required: true
    },
    // ...
  },
}
相关问题