I'm making a basic blog application(I'm a newcomer to web development,so I'm building thisfor learning reasons, so nothing advanced), and when someone needs to publish something they head over to a"/compose" route. And when they publish a POST request is made to the server like this,
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);
}
});
});
and it works fine as of now(I also use Body-Parser. But I also need to know the time the request was made so I can include the written time in the Blog Post. How can I go about achieving it?
If you're using mongoose
, you can simply add an extra property to your schema:
const { Schema } = require("mongoose");
const MovieSchema = new Schema({
title: String,
content: String,
category: String,
author: String,
date: { type: Date: default: () => new Date() }
});
This will automatically add the date to the new document when it is saved to the database, so you don't have to do it manually.
I think I figured it out , I did it like this(I also updated the post Schema.),
const postCategory = req.body.postCategory;
const postBody = req.body.postBody;
const authorName = req.body.authorName;
const addedDate = new Date();
const addedTime = addedDate.toString();
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,
time : addedTime
});
newPost.save(function(err){
if(!err){
console.log(addedTime);
res.redirect("/");
}
});
} else {
res.send("Post title already exists!Revisit the compose page to publish anything else.")
}
} else {
console.log(err);
}
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.