使用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
相关产品推荐
相关产品推荐

