Using created Time Stamp Instead of Current Date MongooseJS - node.js

When I use the GET request I am trying to have my data appear with my blogpost.date timestamp in mm/dd/yyyy format and show the date when it was created. The issue that I am running into is that my data is appearing with the current date & time and in the full timestamp format. I believe the my mongoose model is correctly set up, but it could be an issue with how I am requesting the data in my routes.js.
1) Should I remove Date.now from my schema to fix the current timestamp issue? 2) Would the date formatting occur in my model or most likely formatting in the routes.js file?
blogModel.js:
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var Schema = mongoose.Schema;
var BlogPostSchema = new Schema({
title: String,
author: String,
tagline: String,
content: String,
category: String,
tags: { type: String, lowercase: true },
date: { type: Date, default: Date.now }
});
BlogPostSchema.plugin( mongoosePaginate );
var Blogpost = mongoose.model("Blogpost", BlogPostSchema);
module.exports = mongoose.model('Blogpost', BlogPostSchema);
routes.js:
var express = require('express');
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
//index
router.use(paginate.middleware(10, 50));
router.route('/')
// START POST method
.post(function(req, res) {
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = req.body.tags; // set the tags
blogpost.date = req.body.date; // set the date of the post
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog created.' });
});
}) // END POST method
// START GET method
.get(function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
if (err)
res.send(err);
blogpost.title = req.body.title; // get the blog title
blogpost.author = req.body.author; // get the author name
blogpost.tagline = req.body.tagline; // get tagline
blogpost.content = req.body.content; // get the blog content
blogpost.category = req.body.category; // get the category
blogpost.tags = req.body.tags; // get the tags
blogpost.date = req.body.date; // get the date of the post
res.format({
html: function() {
res.render('pages/index', {
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
}); // END res.format(html, json)
}); // END Blogpost.paginate
}); // END GET method

The easiest way to set the date in your Schema is to let the Schema do it by the default option.
date: { type: Date, default: Date.now }
That is enough. You haven't to set it on your blog entry creation.
So remove this line:
blogpost.date = req.body.date; // set the date of the post
If you want to add your own timestamp (what I wouldn't recommend), then just set your data type to String/Number and remove the default option:
date: { type: String }
I would format the date when you get your blogpost(s)
Check this out Timestamp to human readable format
Do you use AngularJs? If so, check the AngularJs date filter out.

Related

Need to do a many comments belong to one article relation MongoDB

I am using Mongoose/MongoDB and I am trying to associate many comments to one article. My app begins by scraping from a website and then the user has the option to save each article that was scraped into the MongoDB. When the user chooses to save one article, I save it into database. So when a user clicks on one of their saved articles, they can comment on them. Each article has its own comment section I need to retrieve the correct comments.
//My post comment request in JS file
function postComment(){
var articleComment = {
comment: $('#comment').val().trim()
}
$.post('/comments/' + articleID, articleComment).done(function(data){
$('.main-popup').fadeOut();
console.log('DONNE', data);
});
}
//Post route in controller
router.post('/comments/:id', function(req, res){
var newComment = new Comment(req.body);
newComment.save(function(err, doc){
if(err){
console.log(err);
}else{
Comment.findOneAndUpdate({ "_id": doc._id }, { "article": req.params.id }).exec(function(err, doc){
if(err){
console.log(err);
res.send(err);
}else{
res.send(doc);
}
});
}
});
});
//Get request to get correct comments when clicked on specific article
function showCommentBox(){
$('.comments').empty();
$('#comment').val("");
articleID = $(this).attr('data-article-id');
$.get('/comments/' + articleID, function(data){
if(data.article){ //This is undefined*********************
for(var x = 0; x < data.comment.length; x++){
$('.comments').append("<div><h2>" + data.comment[x].comment + "</h2><span><button>×</button></span></div>");
}
}
$('.main-popup').fadeIn();
});
}
//Get route in controller
router.get('/comments/:id', function(req, res){
Comment.findOne({ "article": req.params.id }).populate("article").exec(function(err, doc){
if(err){
console.log(err)
}else{
res.json(doc);
}
});
});
//Article Model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ArticleSchema = new Schema({
title: {
type: String
},
link: {
type: String
},
description: {
type: String
},
img: {
type: String
}
});
var Article = mongoose.model("Article", ArticleSchema);
module.exports = Article;
//Comment Model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CommentSchema = new Schema({
comment: {
type: String
},
article: {
type: Schema.Types.ObjectId,
ref: 'Article'
}
});
var Comment = mongoose.model('Comment', CommentSchema);
module.exports = Comment;
First, you're missing $set when you do .findOneAndUpdate. Also I think you should convert a string to Mongo ObjectId before setting it.
So it might look likt this:
const ObjectId = mongoose.Types.ObjectId;
Comment.findOneAndUpdate({ "_id": doc._id }, {$set: {"article": new ObjectId(req.params.id) }})
Also you don't need to make 2 database calls. You could article id before saving newComment and then simply send it as a response like this:
//Please notice that mongoose.Schema.Types.ObjectId and mongoose.Types.Object are different types.
//You need this one here:
const ObjectId = mongoose.Types.ObjectId;
router.post('/comments/:id', function(req, res){
var newComment = new Comment(req.body);
newComment.article = new ObjectId(req.params.id);
newComment.save(function(err, doc){
if (err) {
console.error(err);
res.send(err);
return;
}
res.send(doc);
});
});

Unable to update Mongoose array type field

I am trying to add some object id into array .Here is my model
var mongoose = require('mongoose'),
moment = require('moment-timezone');
var Schema = mongoose.Schema;
var tag = new Schema({
name: String,
urlId: Array,
createdOn : {
type: Date,
default: moment().tz('Asia/Dhaka')
}
});
module.exports = mongoose.model('Tag', tag);
and my router part where I am trying to update urlId field :
.post(function(req, res) {
var url = new URL({title: req.body.title, href: req.body.url});
url.save();
Tag.findOne({name: req.body.tag}, function(err, hiren) {
if(hiren) {
Tag.findByIdAndUpdate({_id: hiren._id}, {$push: {urlId: url._id}}, {safe: true, upsert: true, new: true}); //this line is not working
}
else {
var tag = new Tag({name: req.body.tag, urlId: url._id});
tag.save();
}
});
Is this correct way to update Array type field or I am missing something

How do i add/update ObjectId array in a collection using MongoDB(Mongoose)?

This is What I want as a final result. I have no idea how to update array of indexes.
my Schema is built using mongoose
var postSchema = new Schema({
title: {type:String},
content: {type:String},
user:{type:Schema.ObjectId},
commentId:[{type:Schema.ObjectId, ref:'Comment'}],
created:{type:Date, default:Date.now}
});
var commentSchema = new Schema({
content: {type:String},
user: {type:Schema.ObjectId},
post: {type:Schema.ObjectId, ref:'Post'}
created:{type:Date, default:Date.now}
});
My controllers are:
// api/posts/
exports.postPosts = function(req,res){
var post = new Post({
title: req.body.title,
content: req.body.content,
user: req.user._id
});
post.save(function(err){
if(err){res.send(err);}
res.json({status:'done'});
});
};
// api/posts/:postId/comments
exports.postComment = function(req,res){
var comment = new Comment({
content: req.body.content,
post: req.params.postId,
user: req.user._id
});
comment.save(function(err){
if(err){res.send(err);}
res.json({status:'done'});
});
};
Do I need to use a middleware? or do i need to do something in controller?
What you want is called "population" in Mongoose (see documentation), which basically works by storing references to other models using their ObjectId.
When you have a Post instance and a Comment instance, you can "connect" them like so:
var post = new Post(...);
var comment = new Comment(...);
// Add comment to the list of comments belonging to the post.
post.commentIds.push(comment); // I would rename this to `comments`
post.save(...);
// Reference the post in the comment.
comment.post = post;
comment.save(...);
Your controller would look something like this:
exports.postComment = function(req,res) {
// XXX: this all assumes that `postId` is a valid id.
var comment = new Comment({
content : req.body.content,
post : req.params.postId,
user : req.user._id
});
comment.save(function(err, comment) {
if (err) return res.send(err);
Post.findById(req.params.postId, function(err, post) {
if (err) return res.send(err);
post.commentIds.push(comment);
post.save(function(err) {
if (err) return res.send(err);
res.json({ status : 'done' });
});
});
});
};

Expressjs Turning Dynamic Uppercase and Spaced Route paths into Hyphenated and lowercase Routes

I am running into an issue where I am trying to use the "title" property from my mongoosedb documents as a document path, but with all of the characters lowercase and the spaces replaced with hyphens. I tried to use a solution before, but wasn't able to generate my view and the Url's contained uppercase letters and %20 for the spaces.
Here is my current setup The focus is on the '/blog/:blogpost_title' route:
routes.js:
var express = require('express');
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
//index
router.use(paginate.middleware(10, 50));
router.route('/')
// START GET method
.get(function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
if (err)
res.send(err);
blogpost.title = req.body.title; // get the blog title
blogpost.author = req.body.author; // get the author name
blogpost.tagline = req.body.tagline; // get tagline
blogpost.content = req.body.content; // get the blog content
blogpost.category = req.body.category; // get the category
blogpost.tags = req.body.tags; // get the tags
res.format({
html: function() {
res.render('pages/index', {
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
}); // END res.format(html, json)
}); // END Blogpost.paginate
}); // END GET method
router.route('/admin/posts/create')
// START POST method
.post(function(req, res) {
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = req.body.tags; // set the tags
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.redirect(303, '/'); //NEEDS TO BE CHANGED
});
}) // END POST method
.get(function(req, res) {
res.render('pages/blogpost-create');
});
function getSearchCriteria(params) {
return {
title: params.blogpost_title
};
}
function getBlogpostUpdate(body) {
return {
title: body.title,
author: body.author,
tagline: body.tagline,
content: body.content,
category: body.category,
tags: body.tags
};
}
var blogpostsRoute = router.route('/blog/:blogpost_title');
// to manipulate your route params, use router.param
router.param('blogpost_title', function (req, res, next, blogpost_title) {
req.params.blogpost_title = blogpost_title.toLowerCase();
next();
});
blogpostsRoute
.get(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOne(searchCriteria, function (err, blogpost) {
if (err)
res.send(err);
res.render('pages/blogpost', {
blogpost: blogpost
})
})
})
.put(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
var updated = getBlogpostUpdate(req.body)
Blogpost.findOneAndUpdate(searchCriteria, updated, function (err, updated) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
})
.delete(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOneAndRemove(searchCriteria, function (err, removed) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
//resume
router.get('/resume', function(req, res) {
res.render('pages/resume');
});
module.exports = router;
index.ejs:
<div class="grid">
<div class="col-9-12">
<div class="blog-content">
<% blogpost.forEach(function(blogpost) { %>
<tr>
<td><h2><%= blogpost.title %></h2></td>
<td><h3><%= blogpost.date %></h3></td>
<td><h3 class="blog-category"><%= blogpost.category %></h3></td>
<td><h3 class="blog-tagline"><i><%= blogpost.tagline %></i></h3></td>
<td><p><%=: blogpost.content | truncate:800 | append:'...' %></p></td>
<td>Read More</td>
</tr>
<% }); %>
</div>
</div>
blogModel.js
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var Schema = mongoose.Schema;
var BlogPostSchema = new Schema({
title: String,
author: String,
tagline: String,
category: String,
content: String,
tags: { type: String, lowercase: true },
date: { type: Date, default: Date.now }
});
BlogPostSchema.plugin( mongoosePaginate );
var Blogpost = mongoose.model("Blogpost", BlogPostSchema);
module.exports = mongoose.model('Blogpost', BlogPostSchema);

Expressjs data not being passed to view

I have a route set up to be able to access individual database records based on their ID. On my homepage ('/') I am pulling all of the records, but only showing 10 records per page with express-paginate module. When I click on Read More, I am sent to the appropriate record's page, but for some reason, I am not seeing any of my CSS styles and the data that I'm passing to this view is coming back as undefined. Individual records are being accessed by /blog/blogpost_id
routes.js:
var express = require('express');
var router = express.Router();
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
//index
router.use(paginate.middleware(10, 50));
router.route('/')
// START POST method
.post(function(req, res) {
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = req.body.tags; // set the tags
blogpost.date = req.body.date; // set the date of the post
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog created.' });
});
}) // END POST method
// START GET method
.get(function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
if (err)
res.send(err);
blogpost.title = req.body.title; // get the blog title
blogpost.author = req.body.author; // get the author name
blogpost.tagline = req.body.tagline; // get tagline
blogpost.content = req.body.content; // get the blog content
blogpost.category = req.body.category; // get the category
blogpost.tags = req.body.tags; // get the tags
blogpost.date = req.body.date; // get the date of the post
res.format({
html: function() {
res.render('pages/index', {
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
}); // END res.format(html, json)
}); // END Blogpost.paginate
}); // END GET method
//Route for individual blogs
router.route('/blog/:blogpost_id')
// START GET method blog by ID
.get(function(req, res) {
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
Blogpost.findById(req.params.blogpost_id, function(err, blogpost) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.author = req.body.author; // update the author name
blogpost.tagline = req.body.tagline; // update the tagline
blogpost.content = req.body.content; // update the blog content
blogpost.category = req.body.category; // update the category
blogpost.tags = req.body.tags; //update the tags
blogpost.date = req.body.date; // update the date of the post
//res.json(blogpost);
res.render('pages/blogpost', {
blogpost: blogpost
});
});
}) // END GET method blog by ID
// START PUT method
.put(function(req, res) {
Blogpost.findById(req.params.blogpost_id, function(err, blogpost) {
if (err)
res.send(err);
blogpost.title = req.body.title; // update the blog title
blogpost.author = req.body.author; // update the author name
blogpost.tagline = req.body.tagline; // update the tagline
blogpost.content = req.body.content; // update the blog content
blogpost.category = req.body.category; // update the category
blogpost.tags = req.body.tags; //update the tags
blogpost.date = req.body.date; // update the date of the post
blogpost.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
});
}) // END PUT method
// START DELETE method
.delete(function(req, res) {
Blogpost.remove({
_id: req.params.blogpost_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
module.exports = router;
blogpost.ejs
<html>
<head>
<% include ../partials/head %>
</head>
<body>
<header>
<% include ../partials/header %>
</header>
<div class="grid">
<div class="col-1-1">
<div class="blog-content">
<h1><%= blogpost.title %></h1>
</div>
</div>
</div>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>
You are overwriting your blogpost content in your router.route('/blog/:blogpost_id').get() method. See these lines:
blogpost.title = req.body.title; // update the blog title
blogpost.author = req.body.author; // update the author name
blogpost.tagline = req.body.tagline; // update the tagline
blogpost.content = req.body.content; // update the blog content
blogpost.category = req.body.category; // update the category
blogpost.tags = req.body.tags; //update the tags
blogpost.date = req.body.date; // update the date of the post
…you're overwriting the blogpost that you just got with (most likely) empty variables, since this is in your GET method.

Resources