显示自mongodb对象的时间戳+重新格式化时间戳以来经过的时间

时间:2017-03-24 08:47:40

标签: javascript mongodb mongoose momentjs ejs

我正在创建一个博客,在博客中你可以添加评论(显然)。在我的mongodb架构中,注释对象如下:

var commentSchema = mongoose.Schema({
id: mongoose.Schema.Types.ObjectId,
text: String,
created: {type: Date, default: Date.now},
author: {
    id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    },
    username: String,
    image: String
}
});

我正在提取时间戳(已创建)并在使用以下内容发布评论时显示它:

    <div id="comments">
    <% blog.comments.forEach(function(comment){ %>
    <div class="jumbotron comment">
        <div class="row">
            <div class="col-md-1">
                <img class="comment-ico" src = "<%=comment.author.image%>">
            </div>

            <div class="col-md-7">
                <h4><%=comment.author.username%></h4>
            </div>
            <div class="col-md-4 date">
                 <%= comment.created.toDateString()%>
            </div>
        </div>
    </div>
        <div><p><%=comment.text%></p></div>

但是,这只是以下列格式显示日期:2017年3月24日星期五

我希望显示的是评论发布后的时间。例如:“1分钟前”,“10分钟前”等。我如何使用JS来显示它?

在类似的说明中,如果我想显示日期,我该如何重新格式化为mm / dd / yyyy?

由于

更新

这是我的评论创建路线,存储在routes / comment.js中:

router.post("/", middleware.isLoggedIn, function(req, res){
// lookup blog using id
Blog.findById(req.params.id, function(err, blog){
    if(err) {
        console.log(err);
        res.redirect("/blogs");
    } else {
        // create new comment
        Comment.create(req.body.comment, function(err, comment){
            if(err) {
                req.flash("error", "Something went wrong");
                console.log(err);
            } else {
                comment.author.id = req.user._id;
                comment.author.username = req.user.username;
                comment.author.image = req.user.image;
                comment.save();
                // connect new comment to campground
                blog.comments.push(comment);
                blog.save();
                var commentCreated = comment.created.toDateString();
                if(req.xhr){
                    res.json({comment: comment, commentCreated: commentCreated, blog: blog});
                } else {
                //     // redirect to campground show page
                    req.flash("success", "Successfully added comment");
                    res.redirect("/blogs/" + blog._id);
                }
            }
        });
    }
});
});

然后我在一个单独的文件(/public/ajax.js)中使用AJAX来异步显示:

$('#newComment').submit(function(e){
e.preventDefault();
var formData = $(this).serialize();
var formAction = $(this).attr('action');
$.post(formAction, formData, function(data){
   console.log(data);
   $("#comments").append(
       `<div class="jumbotron comment">
            <div class="row">
                <div class="col-md-1">
                    <img class="comment-ico" src = "${data.comment.author.image}">
                </div>

                <div class="col-md-7">
                    <h4>${data.comment.author.username}</h4>
                </div>
                <div class="col-md-4 date">
                   ${data.commentCreated}
               </div>
           </div>
        </div>
        <div id="A<%=comment._id%>"><p>${data.comment.text}</p></div>
            <form id="edit-comment-form" action = "/blogs/data._id %>/comments" method = "POST" id="newComment">
            <textarea class = "form-control" rows="4" placeholder = "Type comment here..." name = "comment[text]"></textarea>
            <button class = "btn btn-lg btn-primary btn-block">Submit</button>
            </form>
        <div class="row" id="B${data.comment._id}">
            <div class="col-md-1 choice">
                <a class="edit">Edit</a>
            </div>
            <div class="col-md-1 choice1">
                <form id = "delete-form" action = "/blogs/${data.blog._id}/comments/${data.comment._id}?_method=DELETE" method = "POST">
                    <input type = "submit" class = "button-delete" value = "Delete">
                </form>
            </div>
        </div>

        <hr class = "style-three">`
       );
       $('#newComment').find('.form-control').val('');
});
});

1 个答案:

答案 0 :(得分:3)

moment 对象注入到ejs模板中,这些模板操作日期对象以显示不同的格式。例如:

var moment = require('moment');
var Blog = require('./models/blog');

exports.index = function(req, res) {
    Blog.find().exec(function(err, blogs){
        if (err) throw err;
        // send moment to your ejs
        res.render('index', { moment: moment, blogs: blogs });
    });
}

在您的模板中,使用fromNow() API显示timeago或相对时间:

<div id="comments">
    <% blog.comments.forEach(function(comment){ %>
    <div class="jumbotron comment">
        <div class="row">
            <div class="col-md-1">
                <img class="comment-ico" src = "<%=comment.author.image%>">
            </div>

            <div class="col-md-7">
                <h4><%=comment.author.username%></h4>
            </div>
            <div class="col-md-4 date">
                Created <%= moment(comment.created).fromNow(true) %> ago                 
            </div>
            <!--<div class="col-md-4 date">
                Created at <%= moment(comment.created).format('Do MMM YYYY') %>                 
            </div>-->               
        </div>
    </div>
<div><p><%=comment.text%></p></div>

另一种方法是创建一个将从现在返回的ejs过滤器函数:

<强>的JavaScript

var ejs = require('ejs');
var moment = require('moment');

ejs.filters.fromNow = function(date) {
    return moment(date).fromNow();
}

<强>模板

<div class="col-md-4 date">
    Created <%= comment.created | fromNow %> ago                 
</div>

请记住将时刻添加到package.json文件中:

npm install moment

更新

使用您的实际代码,您只需要在创建commentCreated变量的行上使用moment对象:

// create new comment
Comment.create(req.body.comment, function(err, comment){
    if(err) {
        req.flash("error", "Something went wrong");
        console.log(err);
    } else {
        comment.author.id = req.user._id;
        comment.author.username = req.user.username;
        comment.author.image = req.user.image;
        comment.save();
        // connect new comment to campground
        blog.comments.push(comment);
        blog.save();
        var commentCreated = moment(comment.created).fromNow(); // use moment here
        if(req.xhr){
            res.json({comment: comment, commentCreated: commentCreated, blog: blog});
        } else {
        //     // redirect to campground show page
            req.flash("success", "Successfully added comment");
            res.redirect("/blogs/" + blog._id);
        }
    }
});