So, I'm new to Node.JS, and this project is a simple petshop, with pets table, services offered, and appointments (when a certain service is applied to a certain pet in a certain date in the future).
Appointments have a petId and serviceId, each appointment must have only one of those, but pets and services can be referenced in multiple appointments.
This project was originally made with pure MySql, with separate repositories to handle queries, later I changed it to use sequelize ORM.
I've made the basics crud operations using the rest architecture, everything ok with the services and pets methods (post, get, patch, delete), but the problem began when trying to make post method with appointments, since appointments have serviceId and petId.
index.js
const customExpress = require('./config/customExpress');
const connection = require('./infrastructure/database/connection');
connection.sync()
.then(() => {`
console.log('Successfully connected to database')
const app = customExpress()
app.listen(3000, () => console.log('Server running at port 3000'))
})
.catch(erro => console.log('Something went wrong while trying to synchronize to database'))
connection.js
here is where the associations between tables are made, I think the error might be here, but can't figure out where
const Sequelize = require('sequelize')
const config = require('config')
const { applyExtraSetup } = require('../../models/extraSetup')
const sequelize = new Sequelize(
config.get('mysql.database'),
config.get('mysql.user'),
config.get('mysql.password'),
{
host:config.get('mysql.host'),
dialect:config.get('mysql.dialect')
}
)
const modelDefiners = [
require('../../models/appointments'),
require('../../models/pets'),
require('../../models/services'),
]
// it gets the models definitions and pass the above instance of sequelize to them
for (const modelDefiner of modelDefiners){
modelDefiner(sequelize)
}
// and then make their relations with extra setup
applyExtraSetup(sequelize)
.then(module.exports = sequelize)
and this is appointment.js, a controller that handles the /appointments route and call the sequelize methods
app.post('/appointment', async (req, res) => {
const data = req.body
const pet = await Pets.findAll({ where : { name : req.body.petId }})
const service = await Service.findAll({ where : { name : req.body.serviceId }})
const appointment = Appointment.create(data)
.then(result => {
result.setPet(pet)
res.end()
})
reading sequelize documentation, I saw that with this type of association, you get magic methods to handle data from the related tables, which you call from an instance of a model (setPet, getPet, and so on).
Can anyone help me?