【问题标题】:SequelizeValidationError "userId cannot be null"SequelizeValidationError "userId 不能为空"
【发布时间】:2022-04-11 04:49:37
【问题描述】:

我正在从事一个社交网络项目。我正在用 postman 测试我的请求,但是当我在 postman 上测试我的 createPost 请求时出现问题,我收到错误。

我的邮递员请求:

{
    "title": "Un titre",
    "content": "un contenu",
    "picture": "une image",
    "usersId": 1
}

邮递员出错:

{
    "error": {
        "name": "SequelizeValidationError",
        "errors": [
            {
                "message": "Post.UserId cannot be null",
                "type": "notNull Violation",
                "path": "UserId",
                "value": null,
                "origin": "CORE",
                "instance": {
                    "id": null,
                    "title": "Un titre",
                    "content": "un contenu",
                    "picture": "une image",
                    "updatedAt": "2022-02-08T14:28:08.444Z",
                    "createdAt": "2022-02-08T14:28:08.444Z"
                },
                "validatorKey": "is_null",
                "validatorName": null,
                "validatorArgs": []
            }
        ]
    }
}

这是我的代码:

型号:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Post = sequelize.define('Post', {
    title: DataTypes.STRING,
    content: DataTypes.STRING,
    picture: DataTypes.STRING,
    usersId: DataTypes.INTEGER
  }, {});
  Post.associate = function(models) {
    models.Post.belongsTo(models.User, {
      foreignKey: { //application clé étrangère posée sur la table
        allowNull: false
      }
    });
  };
  return Post;
};

控制器:

const models = require('../models');

exports.createPost = (req, res, next) => {
    let title = req.body.title;
    let content = req.body.content;
    let picture = req.body.picture;
    let usersId = req.body.usersId;

    models.Post.create({ title: title, content: content, picture: picture, usersId: usersId})
    .then((response) =>{
        res.status(201).json(JSON.stringify(response));
    })
    .catch((error) =>{
        console.error(error);
        res.status(400).json({ error })
    })
    .catch(error => res.status(500).json(error))
};

非常感谢您的帮助(我还是个初学者,肯定会有一些错误)。

【问题讨论】:

    标签: sql express sequelize.js postman


    【解决方案1】:

    如果模型中描述了显式外键字段,则需要在关联中指明:

    models.Post.belongsTo(models.User, {
          foreignKey: { //application clé étrangère posée sur la table
            allowNull: false,
            name: 'usersId'
          }
        })
    

    【讨论】:

    • 您好,感谢您的回答,我已尝试按照您的建议进行修复,但在提出请求时一直出现此错误。
    • 你确定你在别处没有Post.belongsTo吗?错误是否具有完全相同的 pathmessage 值?
    • 是的,我很确定:/
    • 你有User.hasMany(Post 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 2017-06-16
    • 2020-10-06
    相关资源
    最近更新 更多