Home > Mobile >  Sequelize set add
Sequelize set add

Time:09-05

I'm sorry for the mistakes in the text because this is my first time in stackoverflow. I have a problem with these methods 'set' and 'add'. I'm trying to use those metods for learn but an error appears

    await Bar.setFoo(' Foo');
              ^

TypeError: Bar.setFoo is not a function

"use strict"

const {Sequelize, DataTypes} = require('sequelize');
const sequelize = new Sequelize("node_test", "node", "****", {
    host: 'localhost',
    dialect: "mysql"
});
const Foo = sequelize.define(
    'Foo',
    {
        name: {
            type: DataTypes.STRING,
            unique: true,
        },
    },
    {
        timestamps: false,
    }
);
const Bar = sequelize.define(
    'Bar',
    {
        title: {
            type: DataTypes.STRING,
            unique: true,
        }
    },
    {
        timestamps: false,
    }
);
const Baz = sequelize.define(
    'Baz',
    {
        summary: {
            type: DataTypes.STRING,
            
        },
    },
    {
        timestamps: false
    }
);
Foo.hasOne(Bar, { sourceKey: 'name', foreignKey: 'fooName' });
Bar.hasMany(Baz, { sourceKey: 'title', foreignKey: 'barTitle'});
 async function a()  {
    //await sequelize.sync({ force: true });
    await Foo.findOne({where: {
        id: 1
    }});
    await Bar.setFoo(' Foo');
    await Bar.addBar('  Bar');
};
a(); 
How can I solve my problem? Thanks to everyone who took the time.

CodePudding user response:

Seems like you misunderstood the concepts of sequelize.
The methods (mixins) you are trying to use should be called from the instance of models not models itself.

Let's say we have model A and model B.
And they have one-to-many relation.

A.hasMany(B);
B.belongsTo(A);

Now if we want to add some instances of B to A, we have to use mixins.

For example if we don't have any records in database we have to create them first.

const a1 = await A.create(); //create one instance of A

const b1 = await B.create(); //create 3 different instances of B
const b2 = await B.create();
const b3 = await B.create();

If we want to add B to A we just call addB from the instance of A.

await a1.addB(b1); //add different instance of B to A separately
await a1.addB(b2);
await a1.addB(b3);

await a1.addBs([b1, b2, b3]); //or batched as array

And if we want to setB i.e. remove all previous and then set new, we just call setB from the instance of A the same way we did before with addB.

await a1.setB(b1);
  • Related