1

I'm using JavaScript and PostgreSQL and I'm wondering if the code and syntax is right written because I'm getting strange errors in different situations.

Example:

function putDbEvents({ description, creatorId, attendeeId }) {
  return pool
    .query(`INSERT INTO events (${description}, ${creatorId}), ${attendeeId}`)
    .then(() => pool.end())
    .catch(console.log);
}

My questions:

  1. should it be {} at the first row of function? I think only ()?
  2. should it be like that insert into or maybe like this INSERT INTO events ('description', creatorId, attendeeId) VALUES then (${}...

This is the create table code:

const createEventsRes = await pool.query(
  "CREATE TABLE IF NOT EXISTS events (id serial PRIMARY KEY, description TEXT, creatorId INTEGER, attendeeId INTEGER)"
);

I wanna create a table so every time you add something it should add an id to it automatically and you just pass description, id, id, to it and the fourth is optional so not needed in this case, and want to see if the syntax is right.

1

2 Answers 2

1

You need to name the columns when inserting:

INSERT INTO events (description, creatorid, attendeeid) 
  values (${description}, ${creatorId}), ${attendeeId})

It's a good practice. And it's also required when you are omitting columns (id in this case).

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

1 Comment

Should it be with ` as well? ` like this: and should it also be {} inside of ()? function putDbEvents({ description, creatorId, attendeeId }) { return pool .query(INSERT INTO events (description, creatorid, attendeeid) values (${description}, ${creatorId} ${attendeeId}) .then(() => pool.end()) .catch(console.log); }
0

Nvm, I solved it.

function putDbEvents(description, creatorid, attendeeid ) { return pool .query(INSERT INTO events (description, creatorid, attendeeid) values ($1, $2, $3), [description, creatorid, attendeeid]) .then(() => pool.end()) .catch(console.log); }

Comments

Your Answer

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