NodeJ和MySQL时间戳

时间:2018-11-16 22:54:56

标签: javascript mysql node.js ejs

我需要创建一个报告,该报告将生成一份教师列表,以及按日期细分的那些教师下访问实验室的学生。

但是目前我正在使用getTime函数添加checkIn和checkOut时间,并在MySQL中将该时间另存为VARCHAR,因为我在MySQL中的时间戳存在问题,每次检入/检出都是它自己的行。我还担心我将无法使用该数据正确生成报告。

当某人在某行中创建检入记录时,当他们后来检出该记录时,我如何才能将其上一行更新为当前日期时间作为checkOut?

// Checking In/Out users
router.post("/checkin", (req, res) => {

const id = req.body.create_id
const firstName = req.body.create_first_name
const lastName = req.body.create_last_name
const checkIn = getDateTime();
const checkOut = getDateTime();

console.log("Checking In...")
console.log("ID: " + req.body.create_id)
console.log("First Name: " + req.body.create_first_name)
console.log("Last Name: " + req.body.create_last_name)
console.log(checkIn)
console.log(checkOut)

// Checking Student In
    if(req.body.person === "Student" && req.body.checkInOut === "checkIn") {
      queryString = "INSERT INTO students ( student_id ,firstName, lastName, checkIn) VALUES(?, ?, ?, ?)"

      getConnection().query(queryString, [id, firstName, lastName, checkIn], (err, rows, fields) => {
        // If error occures 
        if(err) {
          console.log("Failed to check in new user: " + err)
          res.sendStatus(500)
          return
        }
        console.log("Checked in new user with id: ", id)
      })
    }

    // Checking Student Out
    else if(req.body.person === "Student" && req.body.checkInOut === "checkOut") {
      queryString = "INSERT INTO students ( student_id ,firstName, lastName, checkOut) VALUES(?, ?, ?, ?)"

      getConnection().query(queryString, [id, firstName, lastName, checkOut], (err, rows, fields) => {
        // If error occures 
        if(err) {
          console.log("Failed to check out new user: " + err)
          res.sendStatus(500)
          return
        }
        console.log("Checked out user with id: ", id)
      })
    }

1 个答案:

答案 0 :(得分:0)

您还可以像创建表

CREATE TABLE `students` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(128) NOT NULL DEFAULT '',
  `is_checkout` boolean NOT NULL DEFAULT FALSE,
  `last_name` varchar(128) NOT NULL DEFAULT '',
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) CHARSET=utf8mb4 COLLATE utf8mb4_general_ci;

当用户检入仅创建一行时,mysql的current_timestamp将记录当前日期时间 当用户结帐时,您会找到ID为where student.is_checkout = false的学生,并将列is_checkout更新为true,届时update_at将记录结帐日期的当前时间戳