简体   繁体   中英

nodejs express postgresql create use in db user table

What is a practical way to check if a user is already in the db before trying to insert the information for a "new user"

Here is my get user by id and insert function:

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

    pg.query('SELECT * FROM geodate.users WHERE attuid = $1', [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 ($1,$2,$3,$4) 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}`)
    })
}

Thanks

rf guy, Nice shades. First select the user from the geodata.users table. If the user exists, you should not add the user. I don't use pg to query postgres, so I really don't know how it works, but you should be able to do this:

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

  pg.query('SELECT * FROM geodate.users WHERE attuid = $1', [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 ($1,$2,$3,$4) 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"})
      } }) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM