reactjs - 如何传入当前日期 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');
});
});
解决方案
日期是一个变量主题,远远超出了这个问题的范围。如果您要支持多个时区,以这种方式执行日期可能会给您带来麻烦。
在客户端生成日期时,它将绑定到该用户的区域设置。我强烈建议不要这样做,因为它会导致日期跳转到相同的评论字符串(取决于用户评论的时区)。
我会让您发送此消息的端点处理生成日期,以使其保持一致。您也可以考虑将其标准化为 UTC 而不是服务器时间(以防您的服务器时间由于更新或问题而发生变化)。
我不确定您使用的是哪种服务器端语言,但在 JS 中执行此操作将是:
const date = new Date().getTime();
这将为您提供那个确切时刻的时间戳。
推荐阅读
- asp.net-core - Asp.net core web-api http 基于动作的授权
- java - 如何使用线程同步方法进行如下打印?
- c# - 单击按钮-> 保存下一个用户击键
- java - 为什么我的程序只显示我的数组之一
我所有的哈希图数据中的食物而不是实际值? - rest - 具有身份验证用户令牌的 Jenkins 作业 API 不起作用
- python - ValueError: int() 以 10 为底的无效文字:'6_0'
- java - 处理 gRPC 中的异常
- node.js - 如何为 Google Cloud Function Firestore 触发器使用可重用代码?
- eclipse-hono - 如何知道网关模式下的设备连接数?
- java - PDFBOX Flatten Acro-form 导致文本从原始位置移位