在Express/Mysql中,我尝试通过id检索用户。在Postman中,我检索用户并获得如下数据:
"id": {
"type": "Buffer",
"data": [
99,
98,
48,
99,
52,
97,
100,
48,
45,
52,
52,
56,
102,
45,
52,
57
]
},
"email": "user3@gmail.com",
...在SQL中,当我检索用户时,我得到的I是:"0x63623063346164302D343438662D3439",我不能用它来查询。
下面是创建该表的迁移过程:
exports.up = function(knex, Promise) {
return knex.schema.createTable('users', function(table) {
table.binary('id', 16).primary();
table.string('email').notNullable();
table.string('username');
table.string('password').notNullable();
table.timestamp('created_at').defaultTo(knex.fn.now())
table.timestamp('last_login').defaultTo(knex.fn.now())
})
}
exports.down = function(knex, Promise) {
return knex.schema.dropTable('users');
}不确定我做错了什么。
添加路由信息和创建用户的方法,这样我就可以获得更多关于如何应用以下答案的指导。用户注册路由:
router.post("/", auth.optional, async (req, res, next) => {
const {
body: { user }
} = req;
console.log(
"In post new user, this is the req received from Vue: ",
req
);
...
const finalUser = await authHelpers.createUser(req, res);
console.log("In creat user route, The finalUser is " + finalUser);
res.json({ user: authHelpers.toAuthJSON(finalUser) });
});createUser方法:
async function createUser(req, res) {
const salt = bcrypt.genSaltSync();
const hash = bcrypt.hashSync(req.body.user.password, salt);
console.log('helpers.js assigning this value to hash: ', hash)
let newUser = await User.query()
.insert({
id: uuid.v4(),
email: req.body.user.email,
password: hash,
username: req.body.user.username,
slug: slugify(req.body.user.username)
});
console.log("helper.js creating new User: ", newUser);
return newUser;
}发布于 2020-07-22 10:45:24
您需要使用MySQL函数BIN_TO_UUID和UUID_TO_BIN。
BIN_TO_UUID -从数据库检索binary列时使用此函数
SELECT BIN_TO_UUID(userIdBinary) userIdStringUUID_TO_BIN -此函数可用于在数据库或WHERE子句中保存二进制数据(但是,由于MySQL错误,它不使用索引-至少在MySQL 5.7中!)
WHERE userId = UUID_TO_BIN('string_of_binary_userId')MySQL 8内置了对此的支持:
https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html
在MySQL 8之前,您可以自己创建函数。按照这里的说明操作,或者在stackoverflow上搜索它。
https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/
发布于 2020-07-23 20:34:23
现在我知道您正在使用express,我建议使用binary-uuid-ts npm包。在insert中,您应该将uuid转换为二进制:
.insert({
id: uuidToBinaryUUID(uuid.v4()),
email: req.body.user.email,
password: hash,
username: req.body.user.username,
slug: slugify(req.body.user.username)
});您可以通过binaryUUIDToUUID将二进制文件转换回节点中的字符串。或者,您可以将它转换回MySQL中的字符串(上面关于MySQL错误的警告是在WHERE子句中不使用索引)。
https://stackoverflow.com/questions/63022835
复制相似问题