knex.js - 更新数据的简单方法

时间:2017-03-22 14:53:12

标签: mysql node.js knex.js

我想更新一个名为client的表。以下代码适用于有效的id,但对于无效的id,它只是挂起而不调用catch函数。

knex('client').where('id',id).update({
        name:req.body.name
        }).then(function(numberOfUpdatedRows) {
            if(numberOfUpdatedRows) {
                res.json(success);
                return;
            }
        }).catch(function(err){
            res.status('500');
            res.json(err);
            return;         
        }); 
});

我解决了这个问题:

knex('client').where('id',id).select('id').then(function(id){
        if(id) {
            //update 
        }else {
            //failed
        }
    }).catch(function(err){
        console.log("select id do not exist");
        res.send("do not exist");
    });

对于这种情况,对于无效的ids,knex没有调用catch函数,而是挂起而不是挂起返回id的空值,我用它进行错误检查。
我是初学者,我相信有更好的方法可以做到这一点 有人可以建议一个更好的方法吗? 另外,我在knex documentation中找不到knex如何处理这样的错误情况。那么我在哪里可以找到这些信息,所以我将来可以自己解决这些问题。感谢。

4 个答案:

答案 0 :(得分:0)

knex
.select('id')
.from('client')
.where('id', id')
.then(([row]) => {
  if (!row) {
    console.log("select id do not exist")
    return res.send("do not exist")
  }
  return knex('client')
  .update('name', req.body.name)
  .where('id', row.id)
});

如果我已经知道该行可能不存在,我会将此视为逻辑错误,应由代码处理。

答案 1 :(得分:0)

像这样使用knex

const {id,name} = req.body;
    const subQuery = knex('client').select('id').where({id})
    subQuery.then(response=>{
    if(response.length>0){
        subQuery.update({name})
        .then(resp=>{
            res.json('update done')
        })
        .catch(err=>{res.json(err)})
    }
    else{
        res.json('update failed')
     }
})
.catch(err=>{res.json(err)})

答案 2 :(得分:0)

代码执行没有错,这就是为什么未执行catch方法的原因。捕获更新中未发现错误的一种好方法是这样的

const {name} = req.body;
knex("client")
  .update({name})
  .where({id})
.then(rows => {
  // the argument here as you stated
  // describes the number of rows updated
  // therefore if no row found no row will be updated
  if (!rows){
    return res.status(404).json({success:false});
  }
  return res.json({success:true});
})
.catch( e => res.status(500).json(e)); 

或者如果你喜欢一行

const {name} = req.body;
knex("client")
  .update({name})
  .where({id})
  .then(u => res.status(!!u?200:404).json({success:!!u}))
  .catch(e => res.status(500).json(e));

答案 3 :(得分:0)

一个很好的例子就是这个

db("table")
.update({deleted_at: "now()"})
.where("column", "value");

如果您想了解更多信息,请查看:http://knexjs.org/#Builder-update