我正在编写一个应用程序,让用户发布内容(称为“瞬间”)以及与该内容相关的一个或多个标记。
我有一个3表数据模型(在MySQL中),如下所示:
自动增量设置为: MOMENT_ID和TAG_ID
我试图解决的问题(在NodeJS中)是:如何插入一个新的帖子(在矩表中)和一个或更多的标记(在标签表中),获取它们各自的ID,并在连接表(MOMENT_TAGS)中进行第三次插入?
我已经尝试通过执行三个连续的查询来解决这个问题(使用mysqljs),第一个时刻,然后是标记,然后是MOMENTS_TAGS,但是它失败了,因为虽然第一个结果1. instead返回正确的数字,第二个结果2.instead似乎没有从标记表返回正确的数字,而是只是增加了第一个Result1.sertId。
到目前为止,下面是我的代码(首先,我正试图使它对1个标记起作用):
app.post('/api/post/complex', function(req,res) {
pool.getConnection(function(err, connection) {
var preppedQuery1 = "INSERT INTO MOMENTS (USER_ID, TITLE, CREATE_DATE) VALUES ('justatest@gmail.com','test moment title','2016-08-08')";
connection.query(preppedQuery1, function(err1, result1) {
if (err1) {
res.send('ERROR');
connection.release();
}
else {
var preppedQuery2 = "INSERT INTO TAGS (TITLE, CREATE_DATE,USER_ID) VALUES ('TEST TAG', '2016-09-08','justatest@gmail.com')";
connection.query(preppedQuery1, function(err2, result2) {
if (err2) {
res.send('ERROR');
connection.release();
}
else {
var preppedQuery3 = "INSERT INTO MOMENTS_TAGS (MOMENT_ID, TAG_ID) VALUES (" + result1.insertId + "," + result2.insertId + ")";
//At this point if result.insertId is 100, result2.insertId is always 101 instead of coming from the TAGS table
//Why isn't result2.insertId the auto-incremented number from the TAGS table insert?
connection.query(preppedQuery3, function(err3, result3) {
if (err3) {
res.send('ERROR');
connection.release();
}
else {
console.log(result3); //not really needed
res.send('OK'); //everything worked
connection.release();
}
});
}
});
}
});
});
});发布于 2016-08-16 03:33:39
看起来您已经运行了两次preppedQuery1。
在此输入错误:

(假设这不仅仅是文章中的错误,而且实际上存在于您的源中.)
发布于 2016-08-16 20:21:55
解决方案:在第二次preppedQuery中输入错误(再次使用1,而不是2)。
正在分配测试的东西和正确的insertId。
https://stackoverflow.com/questions/38938868
复制相似问题