Search code examples
node.jsexpresssequelize.js

Sequelize returning true is not working after updating v6 for mysql


I am using sequelize js v6 for MySQL Database. I want to get an updated result when I update the database but it only returns [ undefined, 1 ]

I also read their documentation but they say returning is no longer so which one will support they did not clearly mention.

Here is the link: https://sequelize.org/docs/v6/other-topics/upgrade/#optionsreturning

app.get("/global", async (req, res, next) => {

    const update = await Model.update({ total: 11 }, { where: { id: 172 }, plain: true, 
    returning: true })

    console.log(update)

    res.json({ success: true, data: update })

})


 

Solution

  • The returning option is not supported for MySQL, only Postgres. (See description for options.returning in the Sequelize API docs).

    If you're only updating a single record, you're better off getting a model instance and updating it:

    app.get("/global", async (req, res, next) => {
    
        const modelInstance = await Model.findOne({ where: { id: 172 } });
        modelInstance.set({ total: 11 });
        await modelInstance.save();
        console.log(modelInstance.toJSON());
        
        res.json({ success: true, data: modelInstance })
    });
    

    If you're updating multiple rows, the only way I know of to return the updated rows definitively is to use a list of ids:

    app.get("/global", async (req, res, next) => {
    
        const idObjects = await Model.findMany({
            where: { /* your criteria here */ },
            attributes: ['id'], // we'll only need the ids at first
            raw: true, // tells sequelize to just return plain objects, since we don't need model instances
        });
        const idsToUpdate = idObjects.map(o => o.id);
        const [countUpdated] = await Model.update({ total: 11 }, {
            where: {
                id: idsToUpdate,
            },
        });
        console.log(`Updated ${countUpdated} records`);
    
        const updatedRecords = await Model.findMany({
            where: {
                id: idsToUpdate,
            },
        });
        
        res.json({ success: true, data: updatedRecords })
    });