在尝试向Subjects表中添加新主题时,Postgres认为我想在第0、1和3列中添加一些内容。为什么?
我要用Postman发布一个新用户。在用户路由中,我将用户对象插入用户表中。可行。
第二步是将主题插入subjects
表中(如果该主题尚不存在)。
那是哪里出了问题。
此方法应在subjects
表中插入一个新主题并返回新行:
insertSubject(knex, newSubject) {
return knex
.insert(newSubject)
.into('subjects')
.returning('*')
.then(rows => {
console.log(rows)
return rows[0]
})
},
相反,我在邮递员中收到此消息:
{
"message": "insert into \"subjects\" (\"0\", \"1\", \"2\") values ($1, $2, $3) returning * - column \"0\" of relation \"subjects\" does not exist",
"error": {
"length": 122,
"name": "error",
"severity": "ERROR",
"code": "42703",
"position": "25",
"file": "parse_target.c",
"line": "1034",
"routine": "checkInsertTargets"
}
作为参考,这就是我调用上述方法的方式:
.post(jsonParser, (req, res, next) => {
const { first_name, last_name, email, user_password, gender, tutor, student, fee, in_person, online_medium, subjects } = req.body;
const userFields = { first_name, last_name, email, user_password, gender, tutor, student, fee, in_person, online_medium, subjects };
const newUser = { first_name, last_name, email, user_password, gender, tutor, student, fee, in_person, online_medium };
for (const [key, value] of Object.entries(userFields)) {
if (value === null) {
return res.status(400).json({
error: { message: `Missing ${key} in request body` }
})
}
}
const user = []
UsersService.insertUser(
req.app.get('db'),
newUser
)
.then(res => {
user.push(res)
return SubjectsService.getBySubject(
req.app.get('db'),
subjects
)
})
.then(res => {
//console.log logs the subject I posted with postman
console.log(subjects)
if (typeof res === 'undefined') {
return SubjectsService.insertSubject(
req.app.get('db'),
subjects
)
.then(res => {
console.log("hihi")
})
}
})
.then(response => {
console.log(response)
res
.status(201)
.location(path.posix.join(req.originalUrl, `/${user[0].id}`))
.json(serialize(user))
})
.catch(next)
})
这是我通过邮递员发送的对象:
"first_name": "Felicio",
"last_name": "Heading",
"email": "fheadi0@nyu.edu",
"user_password": "5u2v1E1BKrct",
"online_medium": true,
"in_person": true,
"student": false,
"tutor": true,
"gender": "Male",
"rating": 1,
"fee": 25,
"subjects": "abc"
}
编辑:我仅尝试在主题表中输入subject
。
subjects
的值为abc
。
答案 0 :(得分:1)
错误:
"insert into \"subjects\" (\"0\", \"1\", \"2\") values ($1, $2, $3) returning * - column \"0\" of relation \"subjects\" does not exist"
原因是您要告诉Postgres该表具有要INSERT
values ($1, $2, $3)
插入的列“ 0”,“ 1”和“ 2”。错误告诉您表中不存在这些列。实际上,它在列“ 0”处停止,因为没有意义继续下去。最好的猜测是您正在将INSERT
的值分配给列列表。
答案 1 :(得分:0)
正如@AdrianKlaver在评论中指出的那样,我需要更改插入代码。我这样更新它:
insertSubject(knex, newSubject) {
return knex('subjects')
.insert({subject_name: newSubject})
.returning('*')
.then(rows => {
console.log(rows)
return rows[0]
})
},
它有效!