I'm trying to add new users to the database and have the id automatically iterated. The way I'm trying to do this is run a query first to check the total number of rows and then adding 1 to it to assign as the ID of the user I want to add.
One of the problems I'm having is that in the first query the assignment of newUser.id is block scoped, and I cant access that value outside of it. The id for newUser stays at null, or undefined depending on how I move things around
/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);
});
serialtype, or anidentitycolumn in postgres? Then you don't need to make multiple db requests at all.ERROR: duplicate key value violates unique constraint "users_pkey" DETAIL: Key (id)=(12) already exists. SQL state: 23505idcolumn out of theINSERTstatement so that it uses the generated value as the default