一个请求中的多个查询

Multiple queries in one request

我正在尝试将新用户添加到数据库并自动迭代 ID。我尝试执行此操作的方法是 运行 首先查询以检查总行数,然后向其添加 1 以指定为我要添加的用户的 ID。

我遇到的一个问题是,在第一个查询中,newUser.id 的分配是块范围的,我无法在它之外访问该值。 newUser 的 id 保持为空,或未定义,具体取决于我如何移动东西

/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 (, , , )",
    [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);
    });

the assignment of newUser.id is block scoped, and I cant access that value outside of it.

为此你需要使用 promise 链:

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);
});

I'm trying to add new users to the database and have the id automatically iterated

不要通过两次查询来实现。为此,请在数据库中使用 identity column or sequence

或者至少将两个查询立即加入到 运行 的单个语句中:

db.none(
  "INSERT INTO users(id, name, email, active) VALUES ((SELECT COUNT(*)+1 FROM users), , , )",
  [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。你应该使用 type serial 来代替,然后你就可以避免这一切。