我正在尝试将新用户添加到数据库中,并自动迭代ID。我尝试执行此操作的方式是先运行查询以检查总行数,然后向其中添加1以分配为要添加的用户的ID。
我遇到的问题之一是,在第一个查询中,newUser.id的赋值是块作用域的,我无法在其外部访问该值。 newUser的ID保持为null或未定义,具体取决于我如何移动内容
/add user to DB
router.post("/", (req, res) => {
var newID;
const newUser = {
id: null,
name: req.body.name,
email: req.body.email,
active: true
};
db.result("SELECT COUNT(*) FROM users")
.then(data => {
newID = parseInt(data.rows[0].count) + 1;
newUser.id = newID;
//IF I CONSOLE.LOG(newUser) here then the value for id is 14
});
//IF I CONSOLE.LOG(newUser) here then the value for id is NULL
db.none(
"INSERT INTO users(id, name, email, active) VALUES ($1, $2, $3, $4)",
[newUser.id, newUser.name, newUser.email, newUser.active]
)
.then(data => {
res.status(200).json({ msg: "new user was added" });
})
.catch(error => {
console.log("ERROR", error);
});
newUser.id的分配是块作用域的,我无法在其外部访问该值。
您将需要为此使用诺言链:
db.result("SELECT …")
.then(data => {
newUser.id = parseInt(data.rows[0].count) + 1;
return db.none("INSERT …", newUser);
}).then(data => {
res.status(200).json({ msg: "new user was added" });
}, error => {
console.log("ERROR", error);
});
我正在尝试向数据库中添加新用户并自动迭代ID
不要进行两个查询来实现。为此,请在数据库中使用identity column或sequence。
或至少将两个查询合并为一个语句以立即运行:
db.none(
"INSERT INTO users(id, name, email, active) VALUES ((SELECT COUNT(*)+1 FROM users), $1, $2, $3)",
[newUser.name, newUser.email, newUser.active]
)
.then(data => {
res.status(200).json({ msg: "new user was added" });
}, error => {
console.log("ERROR", error);
});
由于您一次使用多个查询,因此您应该使用一项任务:
await db.task('add-new-user', async t => {
const count = await t.one('SELECT count(*) FROM users', [], a => +a.count);
newUser.id = count + 1;
return t.none('INSERT INTO users(${this:name}) VALUES(${this:csv})', newUser);
});
P.S。您应该改用serial
类型,并避免所有这些。