'Sequelize setter error 'invalid input syntax for integer: "[object Object]"'

I am trying to associate a list of contacts to a customer using the associations setter method, however, it always throws the error 'invalid input syntax for integer: "[object Object]"'.

The relevant query mentioned in the error is: UPDATE "contactperson" SET "refCustomerId"=$1,"updatedAt"=$2 WHERE "id" IN ('[object Object]')

This is how I use the setter:

db.customer.findByPk(customerID, {
            include: [{
                model: db.address,
                as: 'address',
            },{
                model: db.contactoption,
                as: 'contactOptions',
            }, {
                model: db.contactperson,
                as: 'contactPersons',
            }]
        }).then(customer => {
customer.setContactPersons([ { firstName: 'tester', lastName: 'tester', description: 'lorem ipsum' } ]);
});

This is the association:

Customer.hasMany(models.contactperson, {
  foreignKey: 'refCustomerId',
  as: 'contactPersons'
});

Any idea what I'm doing wrong?



Solution 1:[1]

You used set<ModelName>s that just updates a link field of given records. If you need to create contactperson record you need to use createContactPerson instead of setContactPersons (NOTE: you cannot create several records at once).

customer.createContactPerson({
  firstName: 'tester',
  lastName: 'tester',
  description: 'lorem ipsum'
});

compare to:

const contactPerson = db.contactperson.findById(1);
if (contactPerson) {
  customer.addContactPersons([contactPerson.id]);
}

set<ModelName>s - replaces old linked records with the new existing ones add<ModelName>s - adds exisiting records in addition to old ones create<ModelName> - create a new non-existing record in addition to old ones

See hasMany special methods

Solution 2:[2]

Exactly what Anatoly posted. I had method declared on TypeScript like:

declare addPost: HasManyCreateAssociationMixin<PostClass, 'userId'>;

When i changed to:

declare createPost: HasManyCreateAssociationMixin<PostClass, 'userId'>;

Everything works so remember - how you describe name of method its very necesary.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 xxx xxx