【问题标题】:Sequelize model doesn't return in then blockSequelize 模型不会在 then 块中返回
【发布时间】:2019-03-22 13:03:22
【问题描述】:

如果 sequelize 正确更新了一行,我会尝试将结果返回给我的控制器。它在当前代码中有效,但无论是失败还是有效,我都只能返回 true。

我尝试了几种我认为可能可行的不同方式,但除非我硬编码“返回 true”,否则控制器中的所有内容都返回未定义

控制器

const {promisify} = require('util');
const pageSection = promisify(db.pageSection);

exports.updateForm = async function (req, res) {

let result;

try {
   result = await pageSection.updateSection(req);
} catch (err) {
    console.log('** NOT GOOD **', err);
}

   return res.send(result);
}

型号

pageSection.updateSection = function (req) {

    var result;

    pageSection.update ({
        title: req.body.title,
        description: req.body.description,
        icon: req.body.icon
    }, {
        where: {
            id: req.body.id
        }
    })
    .then( updatedRow => {  
        return updatedRow; //Undefined in controller

        sendResult( updatedRow ); //Still undefined

        result = updatedRow; // Still undefined
    })
    .catch(err => {
        console.log('Page Model Error: ', err);
    })

    function sendResult ( updatedRow ) {
       if ( updatedRow ) { return true }

    } //Returns undefined

    return true; //Only thing that works

    return result; //Undefined


}

【问题讨论】:

    标签: express sequelize.js


    【解决方案1】:

    (如果你使用的是postgres)你需要添加

    returning: true,
    plain: true
    

    在 where 子句之后的查询,以便实际返回更新的数据行并设置 plain:true 确保返回的是普通对象。

    所以现在它会变成:

    pageSection.update ({
            title: req.body.title,
            description: req.body.description,
            icon: req.body.icon
        }, {
            where: {
                id: req.body.id
            },
            returning: true,
            plain: true
        })
    

    返回的结果是一个数组,因此您需要访问返回数组的第二个元素以获取更新的行。

    【讨论】:

    • 我仍然得到相同的结果。我应该说,updatedRows 确实返回了一个“1”,但是在“then”语句中返回时,它并没有传递给控制器​​。
    • 抱歉,忘记说明returing: true 是您使用postgres 的时候。如果是这样,你会得到一个数组,其中第一个元素是受影响的行数,第二个元素是更新的行数。
    • 感谢您的帮助!
    • 另外,我注意到在你的 then 块中,你在函数调用之前返回,所以 sendResult 永远不会到达
    • 啊,是的,它实际上并不存在...这些是尝试过的不同方法的示例。所以在 sendResult 函数的例子中,在调用函数之前我不会返回。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 2020-07-03
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多