更新 mysql v6 后,Sequelize 返回 true 不起作用

问题描述 投票:0回答:1

我正在为MySQL数据库使用sequelize js v6。我想在更新数据库时获得更新的结果,但它只返回 [ undefined, 1 ]

我也阅读了他们的文档,但他们说不再返回,所以他们没有明确提及哪一个将支持。

这是链接: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 })

})


 
node.js express sequelize.js
1个回答
0
投票

MySQL 不支持返回选项,仅 Postgres 支持。 (请参阅Sequelize API 文档)。

如果您只更新一条记录,最好获取模型实例并更新它:

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 })
});

如果您要更新多行,我知道明确返回更新行的唯一方法是使用 id 列表:

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 })
});
© www.soinside.com 2019 - 2024. All rights reserved.