Search code examples
javascriptmysqldatabasepostmandml

QueryFailedError: ER_BAD_NULL_ERROR: Column 'user_id' cannot be null


I have 3 files: controller, service and dao. I want to do the function readPost, but when using postman, it seems to be stuck in the createPost function inside postDao. please help me..

DAO


const createPost = async (user_id, contents, posting_id, image_url) => {

  await myDataSource.query(
    `INSERT INTO postings ( user_id, contents ) 
    VALUE (?, ?)`,
    [user_id, contents]
  ),

  const post = await myDataSource.query(
    `INSERT INTO posting_images ( posting_id, image_url )
    VALUE (?, ?)`,
    [posting_id, image_url]
  );
  return post;
};

const readPost = async () => {

  const postings = await myDataSource.query(
    `SELECT 
      p.user_id, u.profile_image, 
      p_i.posting_id, p_i.image_url, p.contents
    FROM users u
    JOIN postings p
    ON u.id = p.user_id
    JOIN posting_images p_i
    ON p.id = p_i.posting_id`
  );
  return postings;
};

module.exports = { createPost, readPost };

Solution

  • Could you try like this?

    Reference mySQL insert

    const createPost = async (user_id, contents, posting_id, image_url) => {
    
      await myDataSource.query(
        `INSERT INTO postings ( user_id, contents ) 
        VALUES (?, ?)`,
        [user_id, contents]
      ),
    
      const post = await myDataSource.query(
        `INSERT INTO posting_images ( posting_id, image_url )
        VALUES (?, ?)`,
        [posting_id, image_url]
      );
      return post;
    };