首页 > 解决方案 > 如何传入当前日期 React JS Mongo

问题描述

我正在使用 mongo 数据库进行评论,我正在尝试显示数据库中每个条目的日期

我有以下 Mongo 架构

let CommentsData = new Schema({
    team_id: {
        type: String
    },
    comment: {
        type: String
    },
    date: {
        type: String
    }
});

module.exports = mongoose.model('Comment', CommentsData);

我在前端有以下函数,当单击按钮插入新评论时调用该函数 - ReactJS 中有一个函数可以用来代替“whatgoeshere”吗?将当前日期(在单击按钮时)插入数据库的日期旁边的部分?

    const CommentInsert = (team_id, comment) => {
        axios
            .post('http://localhost:3999/todos/addComment', {
                team_id: team_id, comment: comment, date: whatgoeshere?
            })
            .then(() => {
                console.log(`Successfully added comment`)
            })
            .catch(error => console.error(`Error adding Comment.`))
    }

我的路线如下图

todoRoutes.route('/addComment').post(function (req, res) {
    let toBeAdded = new Comment(req.body);
    toBeAdded.save()
        .then(() => {
            res.status(200).json({'comment added successfully' });
        })
        .catch(err => {
            res.status(400).send('adding comment failed');
        });
});

标签: reactjsmongodbdatemongoose

解决方案


日期是一个变量主题,远远超出了这个问题的范围。如果您要支持多个时区,以这种方式执行日期可能会给您带来麻烦。

在客户端生成日期时,它将绑定到该用户的区域设置。我强烈建议不要这样做,因为它会导致日期跳转到相同的评论字符串(取决于用户评论的时区)。

我会让您发送此消息的端点处理生成日期,以使其保持一致。您也可以考虑将其标准化为 UTC 而不是服务器时间(以防您的服务器时间由于更新或问题而发生变化)。

我不确定您使用的是哪种服务器端语言,但在 JS 中执行此操作将是:

const date = new Date().getTime();

这将为您提供那个确切时刻的时间戳。


推荐阅读