如何自动计算INSERTET DATE -当前日期



我有一个表:

CREATE TABLE IF NOT EXISTS bands (
id serial PRIMARY KEY,
name VARCHAR UNIQUE NOT NULL,
creationDate DATE not NULL,
years  DATE not NULL
);

我只想通过namecreation date。我想要的是years将返回currentdate - creationDate。问题是,我真的不知道我应该正确地改变我的代码,因为我使用Node project。我的代码是这样的:

const express = require("express");
const app = express();
const pool = require("./db");
app.use(express.json());
// Routes
app.post("/bands", async (req, res) => {
try {
const { name, creationDate } = req.body;
const newBand = await pool.query(
"INSERT INTO bands (name, creationDate,years) VALUES ($1, $2) RETURNING *",
[name, creationDate]
);
res.json(newBand);
} catch (err) {
console.error(err.message);
}
});
app.get("/bands", async (req, res) => {
try {
const allBands = await pool.query("SELECT * FROM bands");
res.json(allBands);
console.log(allBands);
} catch (err) {
console.error(err.message);
}
});
app.get("/bands/:bandsName", async (req, res) => {
console.log(req.params);
const { bandsName } = req.params;
try {
const todo = await pool.query("SELECT * FROM bands WHERE name = $1", [
bandsName,
]);
res.json(todo.rows[0]);
} catch (err) {
console.error(err.message);
}
});
app.put("/bands/:id", async (req, res) => {
try {
const { id } = req.params;
const { name, creationDate } = req.body;
const updateTodo = await pool.query(
"UPDATE band SET name = $1,  creationDate = $2 WHERE id = $3",
[name, creationDate, id]
);
res.json("Udało się, zaaktualizowane");
} catch (err) {
console.error(err.message);
}
});
app.delete("/bands/:id", async (req, res) => {
try {
const { id } = req.params;
const deleteTodo = await pool.query("DELETE FROM bands WHERE id = $1", [
id,
]);
res.json("Usunięto");
} catch (err) {
console.error(err.message);
}
});
app.listen(3000, () => {
console.log("server is listening on port 3000");
});

谁能告诉我我应该在哪里改变我的代码,所以"years"会自动计算,而不需要我把数据放在邮差?

const { name, creationDate } = req.body; 
const d = new Date(creationDate );
const year = d.getFullYear();

创建日期对象并检索年份

相关内容

  • 没有找到相关文章

最新更新