You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Knex事务问题:插入users表的邮箱格式异常求助

问题解决:Knex事务中邮箱被存储为JSON格式

问题原因

你在从login表执行returning('email')后,直接把loginEmail[0]赋值给了users表的email字段。在Knex中,当使用returning指定单个字段时,返回的是包含该字段的对象数组(比如[{email: 'adriana123@email.com'}]),而非单纯的字符串数组。把这个对象插入到email字段,数据库会自动将其序列化为JSON格式存储,就出现了你看到的{"email":"adriana123@email.com"}。

修复后的代码

app.post('/register', (req, res) =>{
     const {email, name, password } = req.body;
     const hash = bcrypt.hashSync(password);
       db.transaction(trx =>{
          trx.insert ({
              hash: hash, // 修正原代码笔误:将has改为hash
              email: email
          })
          .into('login')
          .returning('email')
          .then (loginEmail => {
             return trx('users')
              .returning('*')
              .insert({
                email: loginEmail[0].email, // 提取对象中的email属性值
                name: name,
                joined: new Date()
            }).then(user =>{
                res.json(user[0]);
            })
        })
        .then(trx.commit)
        .catch(trx.rollback)
    })
})

额外优化方案

如果你想让returning直接返回字符串数组,可以改用returning('email').pluck('email'),这样loginEmail就是纯字符串数组,直接用loginEmail[0]即可:

trx.insert({hash, email})
  .into('login')
  .returning('email')
  .pluck('email') // 添加pluck方法提取字段值
  .then(loginEmail => {
    return trx('users').returning('*').insert({
      email: loginEmail[0],
      name,
      joined: new Date()
    })
  })

内容的提问来源于stack exchange,提问作者Sebi Popa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 23:30:05