首页 > 解决方案 > 如何在 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。但我还需要知道提出请求的时间,以便我可以在博客文章中包含书面时间。我该如何实现它?

标签: javascriptnode.jsexpressejsbody-parser

解决方案


如果您正在使用mongoose,您可以简单地向您的架构添加一个额外的属性:

const { Schema } = require("mongoose");

const MovieSchema = new Schema({
    title: String,
    content: String,
    category: String,
    author: String,
    date: { type: Date: default: () => new Date() }
});

这会在新文档保存到数据库时自动将日期添加到新文档中,因此您不必手动执行此操作。


推荐阅读