检索执行 http post 请求的日期时间

Retrieve date time doing http post request

我有一个 table 和一个检索数据并将它们发送到数据库的表单。提交表单后,将使用刚刚提交的数据创建新的 table 行。

我想为每行添加一个字段,其中包含提交的日期和时间。

如果我点击提交按钮,我会发出一个 http post 请求。

是否可以保存提交的时间和日期? 我在数据库中使用猫鼬,在路由器中使用 express。

import Router from 'express';
const router = Router();

router.post('/', isAuthorized(), async (req, res) => {
    try {
        let fruit = new Fruits(req.body);
        await fruit.save();
        res.json(fruit);
    } catch (err) { res.status(503).send(err); }        
});

您可以使用 Date 对象获取日期和时间。

将以下代码传递到要保存的代码中。 (喜欢MongoDB)

let date_ob = new Date();

阅读更多关于 Date

您可以使用猫鼬模型在 server-side 上设置 POST 请求的时间戳。

在您的 mongoose Fruits Schema 中,您可以添加一个 timestamps 字段,默认设置为 new Date()。所以像这样:

const mongoose = require("mongoose");

const FruitSchema = new mongoose.Schema({
    ... other Fruit properties...
    timestamps: { type: Date, default: () => new Date() }
});

或者,您可以利用 mongoose 的内置 timestamps,将第二个对象传递给 Schema,如下所示:

const mongoose = require("mongoose");

const FruitSchema = new mongoose.Schema({
    ... Fruit properties ...
}, {
    timestamps: true
});

这会自动将 createdAtupdatedAt 添加到您新创建的 Fruits 文档中。