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

使用Node.js+Postman向PostgreSQL注册用户时邮箱格式异常

解决PostgreSQL插入邮箱字段显示为JSON对象的问题

你遇到的问题是插入邮箱到users表时,字段被存成{"email":"john@gmail.com"}这种JSON格式,而非预期的纯字符串邮箱地址。

问题原因

代码中在login表插入操作后使用.returning('email'),返回的loginEmail是包含对象的数组,结构为[{email: 'john@gmail.com'}]。你直接将loginEmail[0](即这个对象)赋值给users表的email字段,PostgreSQL自动把对象序列化为JSON格式存储了。

解决方案

修改代码中users表插入部分的email赋值,明确取出对象里的email属性值:

app.post('/register', (req, res) => {
    const { email, name, password } = req.body;

    const hash = bcrypt.hashSync(password); 
    db.transaction(trx => {
        trx.insert({
            hash: 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(users => {
                    res.json(users[0]);
                })
        })
        .then(trx.commit)
        .catch(trx.rollback)
    })
    .catch(err => res.status(400).json('unable to register'))
})

这样插入到users表的就是纯字符串格式的邮箱地址,符合预期结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 19:24:56