javascript - 如何在 node.js 中使用 Javascript 获取发布请求的时间
问题描述
我正在制作一个基本的博客应用程序(我是 Web 开发的新手,所以我出于学习的原因构建它,所以没有什么高级的),当有人需要发布一些东西时,他们会转到“/compose”路线。当他们像这样向服务器发出 POST 请求时,
app.post("/compose",function(req,res){
const postTitle = req.body.postTitle;
const postCategory = req.body.postCategory;
const postBody = req.body.postBody;
const authorName = req.body.authorName;
if (postCategory === "movies"){
MoviePost.findOne({title: postTitle}, function(err, foundPost){
if(!err){
if (!foundPost){
const newPost = new MoviePost({
title: postTitle,
content: postBody,
category: postCategory,
author: authorName
});
newPost.save(function(err){
if(!err){
res.redirect("/");
}
});
} else {
res.send("Post title already exists!Revisit the compose page to publish anything else.")
}
} else {
console.log(err);
}
});
});
到目前为止它工作正常(我也使用 Body-Parser。但我还需要知道提出请求的时间,以便我可以在博客文章中包含书面时间。我该如何实现它?
解决方案
如果您正在使用mongoose
,您可以简单地向您的架构添加一个额外的属性:
const { Schema } = require("mongoose");
const MovieSchema = new Schema({
title: String,
content: String,
category: String,
author: String,
date: { type: Date: default: () => new Date() }
});
这会在新文档保存到数据库时自动将日期添加到新文档中,因此您不必手动执行此操作。
推荐阅读
- flutter - 如何更改 PageView 小部件中 FloatingActionButton 的颜色?
- django - 为每个 Django 视图动态提供 TLS 证书,而不是通过 nginx/gunicorn
- c# - 从给定点 (x,y) 到矩形 C# 宽度的一半查找点
- node.js - 在 sequelize.query 中插入,然后返回插入的行
- rxjs - 具有重试和停止行为的 Rxjs 多文件上传队列
- c# - 访问特定的计时器以通过标签停止它
- azure-data-explorer - 使用 Kusto 查询语言计算每个月的用户数
- c# - 没有多个选项的多个过滤器搜索-ASP.NET MVC
- c# - 如何将泛型方法添加到类中,该方法采用扩展泛型类的类,忽略它的父模板参数?
- typescript - JHipster 使用 cypress 和 JWT 以编程方式登录