SequelizeValidationError "l'ID User cannot be not null"

SequelizeValidationError "l'ID User cannot be not null"

我无法在我的数据库中创建新的 post,我试图在身份验证后检索用户的令牌,但我无法检索它并将其存储在 post 中,因此post 已创建。需要帮忙 我的 post 人工请求:

{
    "content": "my content",
    "likes": 0
    "usersId": 1
}

post人出错:

{
    "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';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Post extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      models.Post.belongsTo(models.User, {
        foreignKey: {
          allowNull: false,
          name: "userId"
        }
      })
    }
  };
  Post.init({
    content: DataTypes.STRING,
    comments: DataTypes.STRING,
    attachment: DataTypes.STRING,
    likes: DataTypes.INTEGER
  }, {
    sequelize,
    modelName: 'Post',
  });
  return Post;
};

控制器:

const models = require('../models');
const  {User, Post} = models;
const jwt = require('jsonwebtoken');

exports.createPost = (req, res) => {
    const token = req.cookies.jwt;
    const decoded = jwt.verify(token, process.env.TOKEN_SECRET);
    const userId = decoded.id
     const userIdFound = await User.findOne({where: {id: userId}});
     const {body} = req;
    const post = Post.create({...body, userIdFound})
    .then((response) =>{
        res.status(201).json(post);
    })
    .catch((error) =>{
        console.error(error);
        res.status(400).json({ error })
    })
    .catch(error => res.status(500).json(error))
};

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

您在调用 create 方法时将 userIdFound 指定为道具(与整个用户模型实例一起使用),但您需要 userId 道具和用户 ID:

const userIdFound = await User.findOne({where: {id: userId}});
const {body} = req;
const post = Post.create({...body, userId: userIdFound.id })

const {body} = req;
const post = Post.create({...body, userId })