Reputation: 1185
I'm currently working on a project in express and I'm using knex.js to handle migrations and queries.
I'm still trying to grasp the concept of promises and how I can run multiple queries with knex.
I have the following code:
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');
});
});
}
however I am returned with the following error:
Unhandled rejection Error: ER_TRUNCATED_WRONG_VALUE_FOR_FIELD: Incorrect integer value: '[object Object]' for column 'user_id' at row 1
In my routes
file I have the following post method:
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')
})
}
})
For reference my users table consists of:
my users_units table consists of:
What am I doing wrong?
Upvotes: 0
Views: 978
Reputation: 3227
unit
is an object, you'll have to access the properties (unit_id) - depending on your db you may also have to do something special to get the result inserted object (instead of just the number of rows). The error you are getting is because knex select resolves an array. You can either do first
or access the first element of the array.
Upvotes: 1