[英]Having trouble inserting documents in mongoDB using mongoose and node.js
[英]Having troubles inserting multiple records at once without using for loop in sql server database using node.js
大家好,我是在節點 js 中使用 mysql 庫的新手,我對在數據庫中一次插入多行的可能性感興趣。 我制作了一個簡單的代碼,它從數據庫表中捕獲用戶注冊 ID,並使用該用戶選擇的角色索引。 現在我想將用戶和角色 ID 添加到分別具有 user_id 和 role_id 的 Role_User 表中。
假設我想在不使用循環的情況下執行 3 次:
Insert Into User_role VALUES (1,20);
Insert Into User_role VALUES (2,20);
Insert Into User_role VALUES (3,20);
,其中第一列的數字 1、2、3 是角色索引。
Error I'm getting is RequestError: Incorrect syntax near '?'.
我怎樣才能使這個查詢工作?
if(req.body.roles){
var sqlQuery = `SELECT ID from Test_user Where email = @email`;
var indexiRola = findPositions(db.ROLES, req.body.roles);
request.input('role', db.sql.NChar, req.body.roles);
request.query(sqlQuery).then(
id => {
let ids = Array(req.body.roles.length).fill(id.recordset[0].ID);
console.log(ids); // [20, 20, 20]
let roleUsers = createSeperateLists(indexiRola, ids);
console.log(roleUsers); // [ [ 1, 20], [ 2, 20], [ 3, 20] ]
var insertQuery = `INSERT INTO Role_User ("role_ID", "user_id") VALUES ?`;
request.query(insertQuery, [roleUsers], function(err, result){
if(err) throw err;
console.log("Successfull insertion");
});
})
}
請檢查它是否有幫助。 當然,我無法檢查它是否運行。
相反,它不完整! request.query
是異步的,必須修改該代碼。
至少,正如我希望的那樣,這段代碼不會闖入RequestError: Incorrect syntax near '?'.
請:
if (req.body.roles) {
var sqlQuery = `SELECT ID from Test_user Where email = @email`;
var indexiRola = findPositions(db.ROLES, req.body.roles);
request.input('role', db.sql.NChar, req.body.roles);
request.query(sqlQuery).then(
id => {
let ids = Array(req.body.roles.length).fill(id.recordset[0].ID);
console.log(ids); // [20, 20, 20]
let roleUsers = createSeperateLists(indexiRola, ids);
console.log(roleUsers); // [ [ 1, 20], [ 2, 20], [ 3, 20] ]
// I removed the double quotes from the names and,
// VALUES (?, ?) - this is the right syntax for SQL
const insertQuery = 'INSERT INTO Role_User (role_ID, user_id) VALUES (?, ?)';
// Then, forEach roleUsers
// By the way, [roleUsers] yields an array of arrays of arrays, not cool
roleUsers.forEach(
roleUser => {
request.query(
insertQuery,
roleUser,
// Oh! Shoot!!! This is async.
// Man, you will have to deal with it.
// Please, share with us the final solution!
function(err, result) {
if (err) throw err;
console.log("Successfull insertion");
}
);
}
);
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.