Reputation: 574
I am new to nodejs and was trying to set up an API server, here is my first attempt. I wanted to use mysql instead of mongo db.
My problem is that 'knex('user').insert({email: req.body.email});' doesn't seem to want to save to the database.
var dbConfig = {
client: 'mysql',
connection: {
host : 'localhost',
user : 'root',
password : '',
database : 'db_nodeapi'
}
};
var express = require('express'); // call express
var bodyParser = require('body-parser'); // call body-parser
var knex = require('knex')(dbConfig); // set up database connection
var app = express(); // define our app using express
app.use(bodyParser.urlencoded({ extended: true })); // configure app to use bodyParser()
app.use(bodyParser.json()); // this will let us get the data from a POST
var router = express.Router(); // get an instance of the express Router
router.use(function(req, res, next) { // middle ware for authentication
console.log(' -Logging- ');
next(); // continue to next route without stopping
});
router.get('/', function(req, res) { // listen for a post on root
res.json({ message: ' -Success- ' });
});
router.route('/user') // set up user route
.post(function(req, res) { // listen for a post on user
console.log(' -Post -'); // report a post
knex('user').insert({email: req.body.email}); // insert user into user table
res.json({ success: true, message: 'ok' }); // respond back to request
});
app.use('/api', router); // register routes beginning with /api
var port = process.env.PORT || 8080; // set server port number
app.listen(port); // setup listener
console.log('Magic happens on port ' + port); // report port number chosen
Problem is I can't get knex to add to the database!
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL,
`email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
Here is the database
Upvotes: 17
Views: 52851
Reputation: 51
So I was seen the above solutions all are good if you want to add more than one field without mentioning each field you can go with the below syntax:
knex('students').insert(req.body).then((newUser) => {
res.json({newUser});
}).catch((e)=>console.log(e));
So here your input tag names should be equivalent to the database table field names
Upvotes: 1
Reputation: 382
Solved try this I think there should be some after hook in knex where we can do this automatically but till then this should works.
knex('users')
.insert(data)
.then(async () => {
const result = await knex.raw('select LAST_INSERT_ID() as id');
const id = result[0][0].id;
const user = await knex.from('users').where('id', id);
res.json({ success: true, message: 'ok', user: user[0] });
});
Upvotes: 2
Reputation: 637
Someone has already given a solution. I am here to talk about why adding a then statement can solve this problem.
In fact, then, catch statement are both ok. Please refer to the knex documentation(http://knexjs.org/#Interfaces-then), which mentions:
Coerces the current query builder chain into a promise state.
So select, update, insert, etc. are just the query statement builder, you have to use then or catch to convert it to promise state.
Examples are as follows:
knex('user').insert({email: req.body.email}) //not working
knex('user').insert({email: req.body.email}).then(()=>{}) //working
knex('user').insert({email: req.body.email}).catch(()=>{}) //working
.then(()=>{
knex('user').insert({email: req.body.email}) //not working
knex('user').insert({email: req.body.email}).then(()=>{}) //working
knex('user').insert({email: req.body.email}).catch(()=>{}) //working
return knex('user').insert({email: req.body.email}) //working
})
Upvotes: 12
Reputation: 793
The problem in your code is that you are missing the ".then" statement, which causes the actual execution of the code.
knex('user').insert({email: req.body.email})
.then( function (result) {
res.json({ success: true, message: 'ok' }); // respond back to request
})
That should work. Since knex.js's insert function is a promise, you need to call .then() to actually call it.
Upvotes: 37
Reputation: 3622
Had similar issue once, try this:
//...
router.route('/user').post(function(req, res) {
knex('user').insert({email: req.body.email}).then(function(ret){
res.json({ success: true, message: 'ok'/*,ret:ret*/});
});
});
//...
Upvotes: 1