Post with Association Node JS

0

I'm trying to do an insert (1-N), I use Node JS 8.9.1 and Sequelize version 4.4.2, PostgreSQL database.

I have a Calendar class with GroupGroup class, that is, a calendar can have N GroupGroup records. Relevant parts of classes:

Schedule class:

module.exports = (sequelize, DataType) => {
    const Agenda = sequelize.define("agenda", {
        id: {
            type: DataType.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        datainclusao: {
            type: DataType.DATE,
        },
        data: {
            type: DataType.DATE,
        },
}, {
        freezeTableName: true,
        tableName: 'agenda',
    },
    );

    Agenda.associate = function (models) {
        Agenda.hasMany(models.agendagrupo, { foreignKey: 'idagenda' });     
    }

GroupGroup Class:

module.exports = (sequelize, DataType) => {
    const AgendaGrupo = sequelize.define("agendagrupo", {
        idagenda: {
            type: DataType.INTEGER,
            primaryKey: true,
            autoIncrement: false
        },
        idpaciente: {
            type: DataType.INTEGER,
            primaryKey: true,
            autoIncrement: false
        },
        situacao :{
            type: DataType.STRING(15)
        },
    }, {
        freezeTableName: true,
        tableName: 'agendagrupo',
    },
);

    AgendaGrupo.associate = function (models) {
        AgendaGrupo.belongsTo(models.agenda, { foreignKey: 'idagenda' });
        AgendaGrupo.belongsTo(models.pacientes, { foreignKey: 'idpaciente' });
    }

    return AgendaGrupo;
}

I am sending a JSON to my API (post) but I do not know the correct syntax of how to persist Agenda and GroupAdd, I found a topic in Stack Overflow where it seems to be exactly what I need, however I've set the route as below but returns the following error:

result.setagendagrupo is not function:

Can anyone using Node JS with Sequelize guide me or an example of how to persist this?

Am I doing the best? Or persist the AgendaGroup alone, anyway any suggestions?

My route code I have so far and gives the error:

.post((req, res) => {
    Agenda.create(req.body)
    .then(result => {
        const agendaGrupo = req.body.agendagrupo.map(e => ({
            idagenda: result.id,
            idpaciente: e.idpaciente,
        }));
        console.log("Grupo: ", agendaGrupo);
        result.setagendagrupo(agendaGrupo).then(result => res.json(result));
    })
    .catch(error => {
        res.status(412).json({msg: error.message});
    });
});
    
asked by anonymous 28.04.2018 / 16:33

0 answers