Reputation: 5772
I'm making a function which will save the messages of my chat app to the database. It looks a bit like this:
let Server = require('../models/Server')
module.exports.sendMessage = (req, res, next) => {
let serverRoom = req.body.serverRoom
let serverId = req.body.server.id
let server = Server.findByPk(serverId).then(result => {
console.log(result.rooms[serverRoom].history)
result.rooms[serverRoom].history.push('Hi')
result.name = 'Test1'
console.log(result.rooms[serverRoom].history)
result.save();
})
.catch(error => {
console.log(error)
})
res.status(200).json({
message: 'Success'
})
}
The server has a JSON column which contains an array of objects which have a history property which is an empty array. In my code, I console.log() the history of room with index of 0, then I push a message 'Hi' to the history of that room and then I console.log() the history again to check if the message was pushed. The console.logs prove that the message was indeed pushed, however, when I try to save() the object to the database, the JSON changes do not save.
However, the name of the result which I also change to 'Test1' in the code actually changes in the database, so the save() function is working but without saving the JSON changes. Any clue why is that happening?
Upvotes: 5
Views: 3648
Reputation: 2171
The issue is in this line:
result.rooms[serverRoom].history.push('Hi');
You have to do explicitly set json objects and any array of json objects via using concat
for example.
More info here: https://sequelize.org/master/manual/upgrade-to-v6.html#-code-model-changed----code-
Upvotes: 3