Search code examples
node.jsexpresssequelize.jsmagic-methods

Sequelize magic method not found using Express and Node.JS


I'm coding an application using Sequelize, Express and Node.JS; after set a OneToMany relationship between User and Product, just like this:

app.js:

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

and from a controller called admin.js I'm trying to create a new Product using a magic method:

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 is triggered after submit a form, the error I'm getting is this:

error

So, my question is: based on sequelize's official documentation, after define a relationship I can use methods for create, edit o search an entity, what am I missing to get access to these methods?

thanks for your comments


Solution

  • even though my model is called Product, the table's name is newproducts, so, in order to solve this I made this change:

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

    After this, problem solved