【问题标题】:Sequelize magic method not found using Express and Node.JS使用 Express 和 Node.JS 找不到 Sequelize 魔术方法
【发布时间】:2026-01-24 22:40:01
【问题描述】:

我正在使用 Sequelize、Express 和 Node.JS 编写应用程序;在 User 和 Product 之间设置 OneToMany 关系后,就像这样:

app.js:

Product.belongsTo(User, { constraints: true, onDelete: 'CASCADE' });
User.hasMany(Product);

我正在尝试从一个名为 admin.js 的控制器中使用魔法方法创建一个新产品:

admin.js:

exports.postAddProduct = (req, res, next) => {
  const title = req.body.title;
  const imageUrl = req.body.imageUrl;
  const price = req.body.price;
  const description = req.body.description;
  req.user.createProduct({
    title: title,
    imageUrl: imageUrl,
    price: price,
    description: description
  })
    .then((result) => {
      console.log("Record successfully created");
      return res.redirect("/admin/products");
    })
    .catch((err) => {
      console.log(err);
    });
};

提交表单后触发postAddProduct,我得到的错误是:

所以,我的问题是:根据 sequelize 的官方文档,在定义关系后,我可以使用创建、编辑或搜索实体的方法,我缺少什么来访问这些方法?

感谢您的cmets

【问题讨论】:

  • req.user sequelize 模型实例吗?
  • console.log(req,user),并且,分享它的日志

标签: node.js express sequelize.js magic-methods


【解决方案1】:

即使我的模型名为 Product,表的名称是 newproducts,所以,为了解决这个问题,我做了这个更改:

req.user.createNewproduct({
    title: title,
    imageUrl: imageUrl,
    price: price,
    description: description   })

问题解决

【讨论】: