[英]Knex NodeJS and inserting into the database
I am new to nodejs and was trying to set up an API server, here is my first attempt.我是 nodejs 的新手,正在尝试设置 API 服务器,这是我的第一次尝试。 I wanted to use mysql instead of mongo db.
我想使用 mysql 而不是 mongo db。
My problem is that 'knex('user').insert({email: req.body.email});'我的问题是 '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!问题是我无法将 knex 添加到数据库中!
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这是数据库
The problem in your code is that you are missing the ".then" statement, which causes the actual execution of the code.您的代码中的问题是您缺少“.then”语句,这会导致代码的实际执行。
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.
由于knex.js的insert函数是promise,所以需要调用.then()来实际调用。
Someone has already given a solution.已经有人给出了解决方案。 I am here to talk about why adding a then statement can solve this problem.
我在这里讲为什么添加一个then语句可以解决这个问题。
In fact, then , catch statement are both ok.事实上,那么, catch语句都可以。 Please refer to the knex documentation( http://knexjs.org/#Interfaces-then ), which mentions:
请参阅 knex 文档( http://knexjs.org/#Interfaces-then ),其中提到:
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.所以select 、 update 、 insert等只是查询语句构建器,你必须使用then或catch将其转换为 promise 状态。
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
})
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 中应该有一些后挂钩,我们可以自动执行此操作,但在那之前这应该可以工作。
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] });
});
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*/});
});
});
//...
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:所以我看到上述解决方案都很好,如果你想添加多个字段而不提及每个字段,你可以使用以下语法 go:
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所以这里你的输入标签名称应该等同于数据库表字段名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.