id: null when creating a new item in sequelize

牧云@^-^@ 提交于 2021-02-07 14:16:35

问题


When I try to create a new Conversation item Sequelize will return an object with id: null eventhough there is an valid id in the database. How can I get Sequelize to return the last inserted id to the newly created item?

Conversation.create({
  type: 'private',
  createdBy: 1,
}).then(conversation => {
  reply(conversation);
});

Will return

{
  "type": "conversations",
  "id": null,
  "createdBy": 1,
  "created_at": "2016-03-18T01:47:48.000Z"
}

My code:

const Conversation = model.define('Conversation', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
  },
  type: {
    type: Sequelize.ENUM,
    values: ['private', 'group'],
    validate: {
      isIn: ['private', 'group'],
    },
  },
  createdBy: {
    type: Sequelize.INTEGER,
    field: 'created_by',
  },
}, {
  tableName: 'conversations',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: false,
  getterMethods: {
    type: () => 'conversations',
  },
});

const User = model.define('User', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
  },
  firstName: {
    type: Sequelize.STRING,
    field: 'first_name',
    allowNull: false,
  },
  lastName: {
    type: Sequelize.STRING,
    field: 'last_name',
    allowNull: true,
  },
  email: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  profileImg: {
    type: Sequelize.STRING,
    field: 'profile_img',
    allowNull: false,
  },
  password: Sequelize.STRING,
}, {
  tableName: 'users',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  getterMethods: {
    type: () => 'users',
  },
});

Conversation.belongsToMany(User, {
  foreignKey: 'conversation_id',
  otherKey: 'user_id',
  through: 'conversation_user',
  timestamps: false,
});

User.belongsToMany(Conversation, {
  as: 'conversations',
  foreignKey: 'user_id',
  otherKey: 'conversation_id',
  through: 'conversation_user',
  timestamps: false,
});

回答1:


Yo need to put autoIncrement: true in id field

id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  }

Personally i would advice to skip the id column as sequalize does it automatically for you and works nicely.

hope it helps :)




回答2:


Problem was my MySQL version (5.6 instead of 5.7), updated it and now I'm getting id's of the created items in the promise.



来源:https://stackoverflow.com/questions/36074800/id-null-when-creating-a-new-item-in-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!