javascriptmysqlnode.jsnode-mysql

node mysql inserting current date


mysql node docs give an example of how to escape and do neat things. I am unable to figure out how to insert the current time using this approach.

var post  = {id: 1, createdDate: 'NOW()'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
});
// Error: ER_TRUNCATED_WRONG_VALUE: Incorrect datetime value: 'NOW()' for column 'createdDate' at row 1

Solution

  • An easy workaround if you do not want to use custom formats would be to generate date on server-side using new Date() :

    var post = {
        id: 1,
        createdDate: new Date()
    };
    var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {});
    

    But keep in mind you can have small delay because of server/network lag.