In my Express API, I want the client to be able to either include their phone number or website address or not include it at all.
This is how the SELECT statements are done:
-- SELECT all users
SELECT * FROM users
ORDER BY user_id ASC;
-- SELECT a user
SELECT * FROM users
WHERE user_id = $1;
This is how the INSERT statement is currently done which defaults any undefined value to NULL:
INSERT INTO users (name, username, email, phone, website)
VALUES ($1, $2, $3, $4, $5) RETURNING *;
This is how the callback function of the POST request is handled:
const createUser = async (req, res, next) => {
const { name, username, email, phone, website } = req.body;
try {
const create = await db.query(insertUser, [
name,
username,
email,
phone,
website,
]);
res
.status(201)
.json({ message: "User Created Successfully!", user: create.rows[0] });
} catch (err) {
// If UNIQUE constraint is violated
if (err.code == "23505") {
uniqueConstraintError(err, next);
} else {
serverError(err, next);
}
}
};
insertUser is the variable that the PostgreSQL statement is stored in.
If I try to add the user's info without entering phone and website (which are optional), the GET requests will still show those columns with the assigned value of NULL:
{
"user_id": 10,
"name": "Bruce Wayne",
"username": "Batman",
"email": "bat@cave.com",
"phone": null,
"website": null
}
Is there any way to not show those NULL values in the SELECT statements and GET something like this instead?
{
"user_id": 10,
"name": "Bruce Wayne",
"username": "Batman",
"email": "bat@cave.com"
}