I'm trying to update a sequelize model (called conversation) whenever I insert a value into its association (called message). The conversation model doesn't automatically update, and I haven't found any useful information in the docs.
const router = require("express").Router();
const { Conversation, Message } = require("../../db/models");
const onlineUsers = require("../../onlineUsers");
// expects {recipientId, text, conversationId } in body (conversationId will be null if no conversation exists yet)
router.post("/", async (req, res, next) => {
try {
if (!req.user) {
return res.sendStatus(401);
}
const senderId = req.user.id;
const { recipientId, text, conversationId, sender } = req.body;
// if we already know conversation id, we can save time and just add it to message and return
if (conversationId) {
const message = await Message.create({ senderId, text, conversationId });
Conversation.update({ })
return res.json({ message, sender });
}
// if we don't have conversation id, find a conversation to make sure it doesn't already exist
let conversation = await Conversation.findConversation(
senderId,
recipientId
);
if (!conversation) {
// create conversation
conversation = await Conversation.create({
user1Id: senderId,
user2Id: recipientId,
});
if (onlineUsers.includes(sender.id)) {
sender.online = true;
}
}
const message = await Message.create({
senderId,
text,
conversationId: conversation.id,
});
res.json({ message, sender });
}
catch (error) {
next(error);
}
});
module.exports = router;
for update you must change or append data into your record and second argument is your condition for filter users (if you didnt pass argument for condition it means you didnt want to filter conversations then updade all of the records
await conversation.update(
{ title: 'sample title' },
{ where: { : 2 } }
)