0

Sometimes, I need to pass a null value from my angular frontend app to my backend(node+mysql). My column table content can be NULL.

I have tried to use: NULL, 'NULL' or empty('') but in all cases I have an exception on server side because mysql throw an invalid column value. The error is:

code: 'ER_TRUNCATED_WRONG_VALUE', errno: 1292,
 sqlMessage: 'Incorrect datetime value: \'\' for column \'DATE_CHECK\' at row 1',
 sqlState: '22007',

How could I do that?

//angular front end controller

var saveItem=async function(row){
        var item={}
        try{
          item.ID=row.ID;
          item.DATE_CHECK=row.DATE_CHECK?moment(row.DATE_CHECK).format('YYYY-MM-DD'):'';
          await  $http.post('/agenda_staff/' + item.ID, item)
        } catch(erro){
           console.log(erro)
        }
}

//node server

router.post('/:id',async (req,res,next)=>{  
    var input = JSON.parse(JSON.stringify(req.body));
    var id = req.params.id;
    try {
       const connection = await pool.getConnection();
       try {
            var data = {
              ID: input.ID
            , DATE_CHECK: input.DATE_CHECK
            };

            var query=await connection.query("UPDATE AGENDA_STAFF set ? WHERE id = ? ",[data,id])
            var ret={success:true, message:'Registro foi atualizado'}
            return res.send(ret);
        } finally {
            pool.releaseConnection(connection);
        }
    } catch (err) {
        if (err instanceof Errors.NotFound)
            return res.status(HttpStatus.NOT_FOUND).send({ success:false, message: err.message, results:err.stack }); // 404
        console.log(err);
        return  res.status(HttpStatus.INTERNAL_SERVER_ERROR).send({ success:false,message: err.message, results:err.stack }); // 500
  }
});

//table def

CREATE TABLE AGENDA_STAFF (
    ID BIGINT AUTO_INCREMENT  NOT NULL
    , DATE_CHECK              TIMESTAMP 
    ,CONSTRAINT PK_STAFF
       PRIMARY KEY ( ID )
)ENGINE=INNODB;

1 Answer 1

1

As the docs said: undefined / null are converted to NULL, not something like string 'null' or empty string ''. so change the code inside the node server.

var data = {
    ID: input.ID,
    DATE_CHECK: input.DATE_CHECK === '' ? null : input.DATE_CHECK
};
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.