0

I'm inserting values into a MySQL database using Nodejs mysql2 library.

Here is an example of a prepared statement:

await conn.execute(
    'INSERT INTO Friends (id, user, name, gender) VALUES (UUID(), ?, ?, ?)',
    [ user, body.name, body.gender ]
);

How can I achieve the above if sometimes the body.gender value is not set? I want several attributes in the http request to be optional and insert all allowed values that have been sent in the http request into the database.

The above code gives an error if I leave body.gender out of the http request.

1 Answer 1

1

If there is no some data in body or not sending some data from the client to register in the database, you have to put a null value for that row in that column. You can use this JavaScript feature to do this:

await conn.execute(
    'INSERT INTO Friends (id, user, name, gender) VALUES (UUID(), ?, ?, ?)',
    [ user || null, body.name || null, body.gender || null ]
);

Using this possibility, in the absence of any of the data sent in the body, its value is undefined and the value of null is placed in the query.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.