在列中对空值进行序列化违反了非空约束

时间:2019-04-20 18:38:43

标签: node.js postgresql sequelize.js

尝试将“赞”与帖子关联时出现此错误。

  

未处理的拒绝SequelizeDatabaseError:列中的空值   “ userId”违反了非空约束

现在,以下代码获取正确的帖子ID和用户ID,我做了console log。我可能做错了什么?

routes / posts.js

router.post('/:userId/like/:postId', (req, res)=> {
    models.Post.findOne({
      where:{
          id: req.params.postId
      }
    })
    .then( (like) => {
        if(like){
            models.Likes.create({
                where:{
                    userId: req.params.userId,
                    postId: req.params.postId
                },
                like:true

            }).then( (result) => {
                res.status(200).send({
                    message: 'You have like this post',
                    like: result
                })
            })
        }
    }).catch( (err) => {
        res.status(401).send({
            message: "Something went wrong",
            err: err
        })
    })

})

这是喜欢迁移

  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Likes', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      like: {
        type: Sequelize.BOOLEAN
      },
      userId: {
        allowNull: false,
        type: Sequelize.INTEGER,
        references: {
          model: 'Users',
          key: 'id'
        }
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Likes');
  }
};

帖子迁移

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Posts', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      title: {
        type: Sequelize.STRING
      },
      post_content: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      userId: {
        type: Sequelize.INTEGER,
        references: {
          model: 'Users',
          key: 'id'
        }
      },
      username: {
        type: Sequelize.STRING
      },
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Posts');
  }
};

类似模型

'use strict';
module.exports = function(sequelize, DataTypes) {
  const Like = sequelize.define('Likes', {
    like:{
      type:DataTypes.BOOLEAN,
      allowNull:true
    }
  }, {});
    Like.associate = function(models) {
        Like.belongsTo(models.User, {
          onDelete: "CASCADE",
          sourceKey: 'userId'

        })
        Like.belongsTo(models.Post, {
          onDelete: "CASCADE",
          sourceKey: 'likeId'

        })
    }
  return Like;
}

Post.model

module.exports = (sequelize, DataTypes) => {
  const Post = sequelize.define('Post', {
    title: DataTypes.STRING,
    post_content: DataTypes.STRING,
    username:  DataTypes.STRING
  }, {});
  Post.associate = function(models) {
    Post.belongsTo(models.User, {  foreignKey: 'userId',  targetKey: 'id' });
    Post.hasMany(models.Likes, {  foreignKey: 'postId',  sourceKey: 'id' });
  };
  return Post;
};

额外

add_postId_to_likes

'use strict';
module.exports = {
  up: function (queryInterface, Sequelize) {
     return queryInterface.addColumn(
      'Likes',
      'postId',
      {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'Posts',
          key: 'id',

        }
      }
    )
  },

  down: function (queryInterface, Sequelize) {
     return queryInterface.removeColumn(
     'Likes',
     'postId'
   )
  }
};

2 个答案:

答案 0 :(得分:0)

在解析器中的create调用中,您没有提供必要的值,没有where子句,但实际上没有为所需的userId提供它的值。.看起来您的模型中唯一的值是您要设置的布尔值< / p>

答案 1 :(得分:0)

我知道了。

我只是用body代替了params的{​​{1}}。

postId

将我喜欢的模型更改为此,我使用的是sourceKey而不是外键

router.post('/like', (req, res)=> {

    models.Likes.create({
        postId: req.body.postId,
        userId:  req.user.id,
        like:true
    }).then( (result) => {
        res.status(200).send({
            message: 'You have like this post',
            like: result
        });
    }).catch( (err) => {
        res.status(401).send({
            message: "Something went wrong",
            err: err
        })
    })

})

所以现在我可以喜欢一个帖子,它将把module.exports = function(sequelize, DataTypes) { const Like = sequelize.define('Likes', { like:{ type:DataTypes.BOOLEAN, allowNull:true }, // userId: { // type: sequelize.INTEGER, // references: { // model: 'Users', // key: 'id' // } // }, }, {}); Like.associate = function(models) { Like.belongsTo(models.User, { onDelete: "CASCADE", foreignKey: 'userId' }) Like.belongsTo(models.Post, { onDelete: "CASCADE", foreignKey: 'likeId' }) } return Like; } postId附加在likes表上。

像这样

enter image description here