我开始构建应用程序的用户身份验证部分,并且我使用PostgreSQL作为数据库。我在PG中设置了一个带有以下代码的表格。这是我用来设置USERS
表的代码。当我在INSERTS
控制台中进行psql
时,一切正常。但是,当我在使用pg
npm软件包并通过客户端实例查询数据库的NodeJS应用程序中执行此操作时,将无法正常工作。
DROP EXTENSION IF EXISTS pgcrypto;
DROP TYPE IF EXISTS genderEnum;
DROP TYPE IF EXISTS roleEnum;
-----------------------------------------------
CREATE OR REPLACE FUNCTION trigger_set_timestamp()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-----------------------------------------------
DROP EXTENSION IF EXISTS pgcrypto;
CREATE EXTENSION pgcrypto;
-----------------------------------------------
CREATE TYPE genderEnum AS ENUM ('male', 'female', 'other');
CREATE TYPE roleEnum AS ENUM ('banned', 'suspended', 'member', 'admin', 'developer');
-----------------------------------------------
CREATE TABLE users
(
id serial NOT NULL PRIMARY KEY,
username varchar(33) NOT NULL UNIQUE,
password varchar(255) NOT NULL,
date_of_birth date NOT NULL,
gender genderEnum NOT NULL,
created_at timestamptz NOT NULL DEFAULT NOW(),
updated_at timestamptz NOT NULL DEFAULT NOW(),
role roleEnum NOT NULL DEFAULT 'member',
description text,
image jsonb,
friends jsonb
);
-----------------------------------------------
CREATE TRIGGER set_timestamp
BEFORE UPDATE ON users
FOR EACH ROW
EXECUTE PROCEDURE trigger_set_timestamp();
命令行(成功)尝试:
INSERT INTO USERS ( username, password, date_of_birth, gender, role, description, friends ) VALUES ( 'Amy', '123456', '02/24/1975', 'female', 'member', 'I am a fun girl.', '["Jack", "Suzie"]' );
INSERT 0 1
SELECT * FROM USERS WHERE username = 'Amy';
id | username | password | date_of_birth | gender | created_at | updated_at | role | description | image | friends
----+----------+----------+---------------+--------+-------------------------------+-------------------------------+--------+------------------+-------+-------------------
9 | Amy | 123456 | 1975-02-24 | female | 2019-08-17 03:19:34.518501-04 | 2019-08-17 03:19:34.518501-04 | member | I am a fun girl. | | ["Jack", "Suzie"]
(1 row)
下面是我目前用于该查询的NodeJS代码。我有包裹在POST方法中的async / await函数。我正在解构req.body
中的值,然后将它们作为参数代替$1, $2, $3...etc
插入到SQL查询中,并用于 NON 必需的值(例如{{1 }},description
和image
),我有一个类似friends
的声明作为后备,以防万一(我不是100%确定需要这样做)。我还进行了一些原始的错误处理,但这只是我需要的一些atm。我将在时间到来时对它进行更新,这对于应用程序而言更为重要。
friends||null
以上NodeJS代码的结果:
router.post("/register", async (req, res) => {
const date = new Date();
const loggableDate = date.toLocaleDateString();
const loggableTime = date.toLocaleTimeString();
const { username, password, date_of_birth, gender, role, description, image, friends } = req.body;
console.log("\nBODY", req.body, "\n");
try {
const user = await database.query(`INSERT into
USERS (
username,
password,
date_of_birth,
gender,
role,
description,
image,
friends
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, [
[username],
[password],
[date_of_birth],
[gender],
[role],
[description || null],
[image || null],
[friends || null]
]
);
if (!user) {
return res.status(404).json({ message: errors.clientSideError404, date: loggableDate, time: loggableTime });
}
return res.status(200).json(newUser.rows[0]);
} catch (error) {
return res.status(500).json({ error: error.stack, date: loggableDate, time: loggableTime });
}
});
当我在PostMan上插入以下对象时(选择了原始数据按钮,则将application / JSON设置为文本类型)。
{
"error": "error: invalid input value for enum genderenum: \"{\"female\"}\"\n at Connection.parseE (/Users/JON-DOE/Desktop/virtual-desktop/Work/app/node_modules/pg/lib/connection.js:604:11)\n at Connection.parseMessage (/Users/JON-DOE/Desktop/virtual-desktop/Work/app/node_modules/pg/lib/connection.js:401:19)\n at Socket.<anonymous> (/Users/JON-DOE/Desktop/virtual-desktop/Work/app/node_modules/pg/lib/connection.js:121:22)\n at Socket.emit (events.js:203:13)\n at addChunk (_stream_readable.js:294:12)\n at readableAddChunk (_stream_readable.js:275:11)\n at Socket.Readable.push (_stream_readable.js:210:10)\n at TCP.onStreamRead (internal/stream_base_commons.js:166:17)",
"date": "8/17/2019",
"time": "3:44:51 AM"
}
我希望找出这种枚举器类型做错了什么。我认为这与我使用PostMan输入数据的方式有关,因为{
"username": "Amy",
"password": "123456",
"date_of_birth": "02/24/1957",
"gender": "female",
"role": "member",
"description": "I am a fun girl",
"friends": ["Jack", "Suzie"]
}
控制台可以正常工作。如果这篇文章冗长,请原谅我。我对后端编程尚不陌生,因此我在这里接受了很多信息,非常感谢您的帮助。仅作记录,用bCryptJS和JWT对用户的密码进行加密,但是现在,我只是想让一个简单的INSERT起作用!
谢谢!
答案 0 :(得分:0)
取消引用后的错误:
error: invalid input value for enum genderenum: "{"female"}"
看起来您尝试插入的值不是female
,而是{"female"}
。观察:
=> create temporary table test (a genderEnum);
=> insert into test values ('female');
INSERT 0 1
=> insert into test values ('{"female"}')
ERROR: invalid input value for enum genderenum: "{"female"}"
所以看起来您的数据不是您想像的那样。