我正在使用NodeJS将数据插入我的数据库。如果用户没有输入date的值,那么""
将被发送到数据库。如果我这样做了,它会给我这个错误,error: invalid input syntax for type date: ""
,我该怎么做?
const addAlbum = (request, response) => {
const { title, date, description, id } = request.body;
for (let i = 0; i < request.body.length; i++) {
db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON
CONFLICT (id) DO NOTHING RETURNING *' , [request.body[i].title, request.body[i].date,
request.body[i].description, request.body[i].id], (error, results) => {
if (error) {
throw error
} else {
console.log('INSERT ' + JSON.stringify(request.body));
}
})
}
}
发布于 2020-02-09 22:56:07
我认为,request.body[i].date
是一个字符串,而且如果表中对应的列类型是date
类型,那么它就应该是YYYY-MM-DD
格式。您应该能够存储日期字符串值,将其转换为date对象。尝试将request.body[i].date
更改为:
new Date(request.body[i].date);
您可以执行以下练习来发挥作用:
const createTableText = `
CREATE TEMP TABLE dates(
date_col DATE,
timestamp_col TIMESTAMP,
timestamptz_col TIMESTAMPTZ,
);
`
// create our temp table
await client.query(createTableText)
// insert the current time into it
const now = new Date()
const insertText = 'INSERT INTO dates(date_col, timestamp_col, timestamtz_col) VALUES ($1, $2, $3)'
await client.query(insertText, [now, now, now])
// read the row back out
const result = await client.query('SELECT * FROM dates')
console.log(result.rows)
// {
// date_col: 2017-05-29T05:00:00.000Z,
// timestamp_col: 2017-05-29T23:18:13.263Z,
// timestamptz_col: 2017-05-29T23:18:13.263Z
// }
https://stackoverflow.com/questions/60130573
复制相似问题