nodejs express postgresql 在数据库用户中创建使用 table

nodejs express postgresql create use in db user table

在尝试插入 "new user"

的信息之前检查用户是否已经在数据库中的实用方法是什么

这是我通过 id 和插入函数获取用户:

const getUserById = (request, response) => {
    const id = parseInt(request.params.attuid)

    pg.query('SELECT * FROM geodate.users WHERE attuid = ', [attuid], (err, res) => {
        if (err) {
            return next(err)
        }
        response.status(200).json(results.rows)
    })
}


const createUser = (request, response) => {
    const attuid = request.body[0].attuid

    pg.query('INSERT INTO geodata.users (attuid, num_queries,created_date,modified_date) VALUES (,,,) RETURNING *', [attuid, 0, moment(new Date()), moment(new Date())], (error, results) => {
        if (error) {
            throw error
        }
        response.status(201).send(`User added with ID: ${results.rows[0].attuid}`)
    })
}

谢谢

rf 家伙, 漂亮的色调。首先 select 来自 geodata.users table 的用户。如果用户存在,则不应添加该用户。我不使用pg查询postgres,所以我真的不知道它是如何工作的,但你应该可以这样做:

const createUser = (request, response) => {   const attuid = request.body[0].attuid

  pg.query('SELECT * FROM geodate.users WHERE attuid = ', [attuid], (err, res)=> {
    if (err) {
        return next(err)
    }
      if(results.rows > 0)
      {

        pg.query('INSERT INTO geodata.users (attuid, num_queries,created_date,modified_date) VALUES (,,,) RETURNING
*', [attuid, 0, moment(new Date()), moment(new Date())], (error, results) => {
          if (error) {
              throw error
          }
          response.status(201).send(`User added with ID: ${results.rows[0].attuid}`)
      })

      }
      else{
    response.status(200).json({"message": "Ha! you are already in the db, silly"})
      } }) }