I am setting up a Node.js API with Knex.js, express.js and body-parser.
Now I want to do a Insert into, using at first
request.body (I´m doing this with postman atm)
and on second Hand another insert into using a select-statement as shown below.
I already tried 2 knex.insert in a row, but it returns just the first one. Do you think I should solve it just with a seperate ALTER TABLE statement when executing createQuestionnaire?
table questionnaire
id,
title, (insert using req.body)
description, (insert using req.body)
created_by_id (fk) (insert using select-statement)
exports.createQuestionnaire = function (req, res) {
// The Code I need to implement
// knex('users').where({
// id: req.session.passport.user
// }).select('id')
//this works fine
knex
.insert(req.body)
.returning('*')
.into('questionnaire')
.then(function (data) {
res.send(data);
})
.catch(function (err) {
console.error(err);
res.set({ 'content-type': 'application/json; charset=utf-8' });
res.end(JSON.stringify({ message: "Failed" }));
});
};
How can I solve it ?
I finally solved it and created multiple promises. When inserting, I used ES6 destructuring as shown in the Code
let createdById = null;
exports.createQuestionnaire = function (req, res) {
//get id by user-login
knex('users').where({
id: req.session.passport.user
}).select('id')
//insert into questionnaire
.then(function (user) {
createdById = user[0].id;
knex
.insert({ ...req.body, created_by_id: createdById })
.returning('*')
.into('questionnaire')
.then(function (data) {
res.send(data)
}