简体   繁体   中英

Can't create object with relation one-to-many

I'm a newbie in sequelize, so got some troubles with the trivial task. I have a db definition:

 items.hasMany(images, {as: 'images', foreignKey: 'itemID'});

When I'm creating an item like this ...

let result = await db.items.create(
      {
        type: req.body.type,
        name: req.body.name,
        images: [req.body.images]
      },
      {
        include: [ {model: db.images,  as: "images" } ]
      }
    );

... I'm getting an error:

TypeError: instance.set is not a function

What could be the problem? Or it is not a correct way of insertion?

SOLUTION

The problem was in the type of object that I pass. I was passing [req.body.images], but it was already an array. So removing [] problem solved.

Thanks to everyone who checked it :)

let result = await db.items.create([
  {
    type: req.body.type,
    name: req.body.name,
    images: [req.body.images]
  },
  {
    include: [ {model: db.images,  as: "images" } ]
  }
]);

Wrap args with array in create function(). Hope it might help u.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM