首页 > 解决方案 > 为什么不能将嵌套 JSON 数据 gps 作为 UNKNOWN 类型插入?

问题描述

我正在尝试将数据从客户端插入到服务器的 PostQSL 数据库中。但是,有一个错误:

服务器错误:

uid: test id
gps: 111
(node:8607) UnhandledPromiseRejectionWarning: error: could not determine data type of parameter $2

为什么我不能将嵌套 JSON 数据 gps 作为 UNKNOWN 类型插入?

客户端(角):

  tracking_info = {
       uid: "test id",
       gps: {
         logitude: 111,
         latitude: 222,
         timestamp: 12345,
       }
     }

  // Send data to server
  api.post('savemessage', tracking_info).share();

服务器 (Node.js)

    ...
    console.log("uid: "+ uid);
    console.log("gps: "+ gps.latitude);

    // insert a new message
    await client.query('INSERT INTO messages(uid, gps) VALUES($1, $2)', [uid, gps])
    ...

PostSQL 表设置:

[Name]        [DataType]
 uid           VARCHAR
 gps           UNKNOWN

标签: node.jspostgresql

解决方案


使用 JSON 数据类型来存储 JSON 数据。

  CREATE TABLE tracking_info (  
    uid UUID NOT NULL,
    gps JSON
  );

您可能需要执行 JSON.stringify。

await client.query('INSERT INTO messages(uid, gps) VALUES($1, $2)', [uid, JSON.stringify(gps)])

阅读更多细节http://www.postgresqltutorial.com/postgresql-json/


推荐阅读