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

在Node.js 18.17.0与MariaDB 10.4中将Buffer转换为UUID

问题描述

环境:Node.js 18.17.0、MariaDB 10.4(XAMPP最新版)
需求:从数据库检索UUID格式的电影ID,期望得到字符串格式的UUID,但查询返回的是Buffer类型数据。

建表SQL

CREATE TABLE movie(
  id BINARY(36) PRIMARY KEY DEFAULT UUID(),
  title VARCHAR(255) NOT NULL,
  year INT NOT NULL,
  director VARCHAR(255) NOT NULL,
  duration INT NOT NULL,
  poster TEXT,
  rate DECIMAL(2, 1) UNSIGNED NOT NULL
);

Node.js 代码

import mariadb from 'mariadb';

const config = {
  host: 'localhost',
  port: 3306,
  user: 'root',
  password: '',
  database: 'moviesdb'
}

const connection = await mariadb.createConnection(config)

export class MovieModel{
  static getAll = async ({genre}) => {
    const result = await connection.query('SELECT id FROM movie')
    console.log(result)
  }
}

当前查询结果

[
  {
    id: <Buffer 63 34 30 30 37 37 37 33 33 31 30 2d 62 31 34 34 66 2d 31 31 65 65 2d 39 64 31 36 2d 34 30 31 36 37 65 61 65 63 66 37 64>
  },
  ...
]

期望结果

[
  {
    id: 'c4077310-b14f-11ee-9d16-40167eaecf7d'
  },
  ...
]
简便解决方法

方法1:SQL层面直接转换

在SELECT语句中使用BIN_TO_UUID()函数,将二进制ID直接转为字符串格式的UUID:

SELECT BIN_TO_UUID(id) AS id FROM movie

执行该查询后,返回的id字段就是期望的字符串UUID,无需后续处理。

方法2:连接配置自动转换

修改数据库连接配置,添加uuidFormat: 'string'参数,让mariadb驱动自动处理二进制UUID的转换:

const config = {
  host: 'localhost',
  port: 3306,
  user: 'root',
  password: '',
  database: 'moviesdb',
  supportBigNumbers: true,
  uuidFormat: 'string' // 开启自动转换二进制UUID为字符串
}

配置完成后,执行原查询语句即可得到字符串格式的UUID。

方法3:手动转换Buffer

如果不想改动SQL或连接配置,可在获取结果后手动将Buffer转为字符串:

const result = await connection.query('SELECT id FROM movie');
const formattedResult = result.map(item => ({
  ...item,
  id: item.id.toString('utf8')
}));
console.log(formattedResult);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 11:55:38