簡體   English   中英

如何使用 node-postgres (pg) 將此 JSONB 正確保存到 PostgreSQL 中?

[英]How do I properly save this JSONB into PostgreSQL using node-postgres (pg)?

因此,我在 GET URL 中有信息,這些信息需要傳遞到 JSON 中,然后在 PostgreSQL 中保存(與增加的 ID 聚合以確保正確) 我寫了下面的代碼,它似乎沒有保存任何沒有錯誤的東西:

// Pg initialization
const { Client } = require('pg')
client = new Client({
    host: 'localhost',
    user: 'postgres',
    password: 'passwordhere',
    database: 'dbnamehere',
});

const createTableText = `
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
CREATE TEMP TABLE IF NOT EXISTS cases (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  data JSONB
);
`

app.get('/test', async function (req, res) {
  data = req.query.data;
  console.log(data);
  res.status(200).send(data);
// create our temp table
await client.query(createTableText)
//const newUser = { email: 'test@test.com' }
// create a new case
await client.query('INSERT INTO cases(data) VALUES($1)', [data])
const { rows } = await client.query('SELECT * FROM cases')
console.log(rows)
  res.end();
});


我的 package.json 依賴項:

"dependencies": {
    "express": "^4.17.1",
    "mongoose": "^5.9.9",
    "pg": "^8.0.3"
  },
  "devDependencies": {}

更新

我在文件末尾有這個錯誤處理代碼:

 // Prints out more detailed errors
  if(process.env.NODE_ENV !== 'production') {
    process.once('uncaughtException', function(err) {
      console.error('FATAL: Uncaught exception.');
      console.error(err.stack||err);
      setTimeout(function(){
        process.exit(1);
      }, 100);
    });
  }

我還嘗試安裝npm install express-promise-router並添加以下代碼但沒有打印錯誤:

var router = require('express-promise-router')();
router.use('/test', function (req, res) {
    return Promise.reject();
})

UPDATE2此代碼不關閉它打印出 JSONB,而不是如何保存它?:

const connectionString=urlhere;
const pool = new Pool({
    connectionString: connectionString,
  })

  const client = new Client({
    connectionString: connectionString,
  })
  client.connect()

更新3:

我刪除了異步代碼並使其同步。 我現在收到以下錯誤消息:

(node:10860) UnhandledPromiseRejectionWarning: Error: Connection terminated
    at Connection.<anonymous> (/path/here/node_mo
dules/pg/lib/client.js:275:34)
    at Object.onceWrapper (events.js:299:28)
    at Connection.emit (events.js:215:7)
    at Socket.<anonymous> (/path/here/node_module
s/pg/lib/connection.js:73:10)
    at Socket.emit (events.js:210:5)
    at TCP.<anonymous> (net.js:659:12)
(node:10860) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
 error originated either by throwing inside of an async function without a catch
 block, or by rejecting a promise which was not handled with .catch(). (rejectio
n id: 1)
(node:10860) [DEP0018] DeprecationWarning: Unhandled promise rejections are depr
ecated. In the future, promise rejections that are not handled will terminate th
e Node.js process with a non-zero exit code.
(node:10860) UnhandledPromiseRejectionWarning: Error: Connection terminated
    at Connection.<anonymous> (/path/here/client.js:275:34)
    at Object.onceWrapper (events.js:299:28)
    at Connection.emit (events.js:215:7)
    at Socket.<anonymous> (/path/here/node_module
s/pg/lib/connection.js:73:10)
    at Socket.emit (events.js:210:5)
    at TCP.<anonymous> (net.js:659:12)
(node:10860) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
 error originated either by throwing inside of an async function without a catch
 block, or by rejecting a promise which was not handled with .catch(). (rejectio
n id: 2)
(node:10860) UnhandledPromiseRejectionWarning: Error: Connection terminated
    at Connection.<anonymous> (/path/here/node_mo
dules/pg/lib/client.js:275:34)
    at Object.onceWrapper (events.js:299:28)
    at Connection.emit (events.js:215:7)
    at Socket.<anonymous> (/path/here/node_module
s/pg/lib/connection.js:73:10)
    at Socket.emit (events.js:210:5)
    at TCP.<anonymous> (net.js:659:12)
(node:10860) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This
 error originated either by throwing inside of an async function without a catch
 block, or by rejecting a promise which was not handled with .catch(). (rejectio
n id: 3)

我有一個使用 express-generator 文件夾結構生成的項目。 但它遵循節點 pg 建議的項目結構。

.
├── _bin
|   ├── www
├── _db
|   ├── index.js
├── _server
|   ├── index.js
├── _sql
|   ├── create.sql
|   ├── insert.sql
|   └── drop.sql
├──.env
├── package.json
└── app.js

數據庫/index.js

const { Pool } = require('pg')
const pool = new Pool()
module.exports = {
  query: (text, params, callback) => {
    return pool.query(text, params, callback)
  },
}

在上面的文件中,憑據由 .env 文件加載。 但是你可以在你的問題中。

服務器/index.js

// notice here I'm requiring my database adapter file
// and not requiring node-postgres directly
const db = require('../db')
app.get('/:id', (req, res, next) => {
  db.query('SELECT * FROM users WHERE id = $1', [req.params.id], (err, res) => {
    if (err) {
      return next(err)
    }
    res.send(res.rows[0])
  })
})

現在在 sql 文件夾中,您應該放置您的 DDL 數據。

sql/create.sql

CREATE TABLE employee(
  employee_id SERIAL PRIMARY KEY ,
  login VARCHAR(20) NOT NULL,
  password VARCHAR(512)
);

在這里,您可以僅使用psql匯總命令,也可以創建一個包裝器以使用 javascript 運行 DDL 並在package.json中使用它

如果你想在 javascript 中做一個包裝器

sql/create.js

const fs = require('fs'),
pg = require('../db/index'),
sql = fs.readFileSync(__dirname + '/../sql/create.sql').toString();

pg.query(sql, (err) => {
    if (err) {
        throw err;
    }
})

現在在腳本部分的 package.json 中,您可以添加一個新行:

package.json

{
  ...
  "name": "myawesomeproject",
  "version": "1.0.0",
  "description": "My wonderful description",
  "main": "app.js",
  "scripts": {
    "start": "node ./bin/www",
    "createdb": "node ./sql/create.js"
  },
  ...
}

現在您可以使用npm run createdb

因此,在您的/test路線中回答真正的問題應該是:

app.get('/test', async function (req, res) {
  try {
    const { rows } = await client.query('SELECT * FROM cases')
    res.status(200).send(rows);
  } catch {
    res.status(500).send("Error. Detail: "+e)
  }    
});
//should insert data with post method, whole body is your current data.
app.post('/adddata', async (req, res) => {
    const data = req.body;
    console.log(data);
    try {
        await client.query('INSERT INTO cases(data) VALUES($1)', [data])
        res.status(201).send('Data inserted');
    } catch (e) {
        res.status(500).send("Error. Detail: "+e)
    }
})

確保您的客戶端正確連接到您的 Postgres 數據庫,嘗試添加一個client.connect()和帶有控制台日志的基本查詢(在您的路由器之外)。

https://node-postgres.com/features/connecting

您的表是否正確創建意味着您已連接到數據庫?

NodeJS 和 DB 在您的計算機上還是在 docker 中?

該請求是否給您任何響應代碼?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM