【问题标题】:Returning updated object after update to database instead of count更新到数据库后返回更新的对象而不是计数
【发布时间】:2020-03-07 03:05:01
【问题描述】:

我正在更新食品卡车数据库中的条目。这是我的模型在此特定更新中的样子:

function editTruck(changes, id) {
    return db('trucks')
        .where({ id })
        .update(changes)
        .then(id => {
            return findTruckById(id);
        })
}

我想以对象形式返回实际更新的条目。正如你在上面看到的,我试图通过在模型中使用另一个名为findTruckById 的方法来实现这一点。这就是findTruckById 的样子:

function findTruckById(id) {
    return db('trucks')
    .select('id', 'name', 'image', 'operator_id', 'cuisine_type', 'physical_address')
    .where({ id })
    .first()
}

这不起作用,因为从 editTruck 方法返回的响应只是数据库中已更新条目的计数,即 1,而不是条目的 id 或 id 数组。因此,它总是只返回 1 并且在 findTruckById 中运行 1 会返回一个与卡车数据库中 id 为 1 的条目等效的对象,这绝对不是我们想要的。我该如何解决这个问题?

【问题讨论】:

    标签: javascript sql node.js database backend


    【解决方案1】:

    你已经有了ID,不需要“更新”来返回它。

    function editTruck(changes, id) {
    return db('trucks')
        .where({ id })
        .update(changes)
        .then(() => { // you already have the id, just use the `id` that is already in the scope
            return findTruckById(id);
        })
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-04
      • 2013-05-31
      • 2016-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      相关资源
      最近更新 更多