尝试将 json 数据保存到数据库时出现 422 错误

422 error trying to save json data to the database

我正在尝试通过 Node 方法将数据保存到我的 MySql 数据库中。这包括一个名为 attachments.

的字段

console.log(JSON.stringify(post.acf.attachments[0])); returns:

{
  "ID": 4776,
  "id": 4776,
  "title": "bla",
  "filename": "bla.pdf",
  "filesize": 1242207,
  "url": "https://example.com/wp-content/uploads/bla.pdf",
  "link": "https://example.com/bla/",
  "alt": "",
  "author": "1",
  "description": "",
  "caption": "",
  "name": "bla",
  "status": "inherit",
  "uploaded_to": 0,
  "date": "2020-10-23 18:05:13",
  "modified": "2020-10-23 18:05:13",
  "menu_order": 0,
  "mime_type": "application/pdf",
  "type": "application",
  "subtype": "pdf",
  "icon": "https://example.com/wp-includes/images/media/document.png"
}

这确实是我要保存到数据库中的数据:

await existing_post.save({
    ...
    attachments: post.acf.attachments[0],
)};

但是,附件字段会产生 422 服务器错误(如果我注释掉此字段,其他字段将毫无问题地保存到数据库中)。我不知道是什么导致了这个错误。有什么想法吗?

我也试过了

await existing_post.save({
    ...
    attachments: post.acf.attachments,
)};

但似乎只是将 "[object Object]" 保存到数据库。

数据库中的字段定义为文本。我也尝试过将字段定义为 json,但这没有任何区别。

exports.up = function (knex, Promise) {
    return knex.schema.table("posts", function (table) {
        table.longtext("attachments");
    });
};

422 错误代码是关于服务器无法处理您发送给它的数据。在您的情况下,当 post.acf.attachments 看起来像一个对象时,您的 table 字段是 longtext。这就是为什么它将 [object Object] 保存到您的数据库(它是 toString() 方法的 return 值)。

尝试使用

await existing_post.save({
    ...
    attachments: JSON.stringify(post.acf.attachments),
)};

MySQL 和 knex 都支持 JSON 格式,我建议您将字段更改为 json。 (参见 knex docs and mysql 8 docs)。你仍然需要将你的对象字符串化。

编辑:我刚刚看到 Knex 支持 jsonInsert(以及许多其他简洁的东西)作为查询构建器,应该对您有用。 Mysql也支持大范围cool stuffs for handling jsons

此外,当您在数据库中获取结果时,您需要解析 JSON 结果以获得实际的 JSON 对象:

const acf = await knex('posts').select('acf').first();
const attachment = JSON.parse(acf.attachment;

Knex 还提供 jsonExtract that should fill your needs (See also the mysql json_extract