I'm trying to make a survey for a specific amount of users. When a user first submits their answers I want to create a new entry in the database, this part works fine. If the same user wants to retake the survey I want to update their answers instead of creating a new entry for the same user.
I'm trying to use sequelize upsert but it keeps creating new entries for the same "testuser" every time I make a new post request.
None of the answers found online seemed to work. Any help on what I might be doing wrong is appreciated.
// parts of the code that might not be relevant to the problem have been omitted
const express = require('express');
const bodyParser = require('body-parser');
const Sequelize = require('sequelize');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const sequelize = new Sequelize({
database: 'database',
username: 'user',
password: 'password',
dialect: 'mysql',
});
sequelize
.authenticate()
.then(() => console.log('Connection has been established successfully.'))
.catch(err => console.log('error: ', err));
const SurveyResults = sequelize.define('results', {
name: {
type: Sequelize.STRING,
primaryKey: true,
unique: true,
},
results: {
type: Sequelize.JSON,
},
});
SurveyResults.sync()
.then(() => console.log('Survey results table created'))
.catch(err => console.log(err));
app.post('/dashboard', (req, res) => {
let { username, surveyData } = req.body;
SurveyResults.upsert(
{
name: username,
results: surveyData,
},
{ name: username }
)
.then(data => console.log(data))
.catch(err => console.log(err));
});
const PORT = process.env.PORT || 5050;
app.listen(PORT, () => console.log('Server is running on port ' + PORT));
Pk doesnt have to be unique, it's redundant.
If username is not primary key, create another unique index on that column and upsert will work as create if same username is not found, update if same username already exists in table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With