How to create and modify the same record with Sequelize?

Asked

Viewed 260 times

-1

I am developing a scheduling system but came across the following difficulty:

In the schedule table (Appointment) has a field quantidade and would like each time a record was created to add +1 in this field, and when that field reached the value 6 return the error 'Agendamento já preenchido'.

However, the function create Sequelize creates a new record with a new id. I would like to edit the record already created, I tried with conditional (if registration exists , do it...), but it did not work.

Any idea how to do this? Follow the code below:

import { startOfHour, parseISO, isBefore } from 'date-fns';
import Appointment from '../models/Appointment';

class AppointmentController {
    async store(req, res) {
        const { date } = req.body;

        const hourStart = startOfHour(parseISO(date));

        // Checando horas vencidas
        if (isBefore(hourStart, new Date())) {
            return res.status(400).json({ error: 'Data vencida' });
        }

        // Checando disponibilidade do agendamento
        const checkAvailability = await Appointment.findOne({
            where: {
                date: hourStart,
                canceled_at: null,
                quantidade: 6,
            },
        });

        if (checkAvailability) {
            return res.status(400).json({ error: 'Agendamento já preenchido' });
        }

        // Criando agendamento
        const appointment = await Appointment.create({
            user_id: req.userId,
            date,
            qualidade: +1,
        });

        return res.json(appointment);
    }
}

export default new AppointmentController();
  • You say you want to add +1 instead of creating a new record. This means you will always have the date availing hourStartand the canceled_at as null? I’m in doubt if you’re having one XY problem there

  • If the scheduling is at the same time I want to add to the +1 quantity field if the time is different then it will be a new record

1 answer

1


Let’s get a few things straight first:

  • The equivalent of INSERT in Sequelize is Modelo.create({ dados }).
  • The UPDATE has two "equivalent" options in Sequelize:
Modelo.update({ nome: "Novo Nome" }, {
  where: { "identificador": "X" }
});

or

const instancia = await Modelo.create({ nome: "João" });
console.log(instancia.nome); // "João"
instancia.nome = "Rafael";
// O nome ainda é "João" no banco de dados
await instancia.save();
// Agora o nome foi atualizado para "Rafael" no banco de dados

Adapting this to your case, one can use a find to find a schedule at the specified time and then make the necessary checks:

//...

// Busca o agendamento no horário especificado
const appointment = await Appointment.findOne({
  where: {
    date: hourStart,
    canceled_at: null
  }
});

if (appointment == null) {
  // Não existe, então cria o agendamento
  const appointment = await Appointment.create({
    user_id: req.userId,
    date,
    qualidade: 1
  });
} else if (appointment.quantidade < 6) {
  // Já existe e é válido, então atualiza a quantidade no banco
  appointment.quantidade += 1;
  await appointment.save();
} else {
  // Possui quantidade >= 6, então retorna o erro
  return res.status(400).json({ error: 'Agendamento já preenchido' });
}

// Retorna o agendamento
return res.json(appointment);

//...
  • 1

    Thanks Rafael, your solution to my question is correct, after applying I identified that this way would not be ideal for my application because it would write everything in only 1 record in the bd, I solved otherwise my new problem but for the issue your code worked, thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.