So I'm sending data from my React app to my PostgreSQL database using NodeJS
ReactJS
let data = files.map(( { name }, index, album_id ) => ({ name, index : index, album_id:
params.albumId }));
let request = new Request(`http://localhost:3000/albums/${params.albumId}/songs`, {
method: 'POST',
headers: new Headers({ 'Content-Type': 'application/json' }),
body: JSON.stringify(data),
});
fetch(request)
.then((response) =>
response.json())
.then((data) => {
})
.catch((error) => {
console.log(error)
})
NodeJS - queries.js
const addSong = (request, response) => {
const id = parseInt(request.params.id)
const { name, link, index, album_id } = request.body;
for (var i = 0; i < request.body.length; i++) {
pool.query('INSERT INTO songs (name, link, index, album_id) VALUES ($1, $2, $3, $4) ON
CONFLICT (index) DO NOTHING RETURNING *', [request.body[i].name, request.body[i].link,
request.body[i].index, request.body[i].album_id], (error, results) => {
if (error) {
throw error
console.log(error)
} else {
console.log("addSong " + JSON.stringify(results.rows) + id);
}
});
}
}
NodeJS - index.js
const app = express();
const db = require('./queries');
app.post('/albums/:id/songs', db.addSong)
The index constraint is a unique constraint saying index can't be added more than once if it has the same value. My issue is the constraint is being set on each object even if the album_id is different but I want each page to be able to have separate index constraints.
Here is what my json looks like from my GET request:
My question is how can I put something in my code in my POST request like INSERT WHERE album_id = id
which id is parseInt(request.params.id)