我目前正在使用快递项目,我正在使用knex.js来处理迁移和查询。
我仍然试图掌握承诺的概念以及如何使用knex运行多个查询。
我有以下代码:
this.addUnit = function(unit_prefixV, unit_nameV, unit_descriptionV, profile_id) {
return knex.insert({ 'unit_prefix':unit_prefixV, 'unit_name':unit_nameV, 'unit_description':unit_descriptionV }).into('units')
.then(function(unit) {
return knex('users').where({ 'google_id':profile_id }).select('id')
.then(function(uid) {
return knex.insert({ 'unit_id':unit, 'user_id':uid }).into('users_units');
});
});
}
但是我返回时出现以下错误:
Unhandled rejection Error: ER_TRUNCATED_WRONG_VALUE_FOR_FIELD: Incorrect integer value: '[object Object]' for column 'user_id' at row 1
在我的routes
文件中,我有以下帖子方法:
app.post('/dashboard/unit/add', ensureAuthenticated, function(req, res) {
let postErrors = []
if (req.body.unit_name.trim() == "") {
postErrors.push('Unit name cannot be empty.')
}
if (req.body.unit_prefix.trim() == "") {
postErrors.push('Unit prefix cannot be empty.')
}
if (req.body.unit_description.trim() == "") {
postErrors.push('Unit description cannot be empty.')
}
if (postErrors.length > 0) {
res.render('addUnit', { errors: postErrors, user: req.user })
} else {
unitModel.addUnit(req.body.unit_prefix.trim(), req.body.unit_name.trim(), req.body.unit_description.trim(), req.session.passport.user.id).then(function(unit) {
res.redirect('/dashboard')
})
}
})
作为参考,我的用户表包括:
我的users_units表包含:
我做错了什么?
答案 0 :(得分:1)
unit
是一个对象,您必须访问属性(unit_id) - 根据您的数据库,您可能还需要做一些特殊的事情来获取结果插入对象(而不仅仅是行数) )。您得到的错误是因为knex选择解析数组。您可以first
或访问数组的第一个元素。