【问题标题】:Display time elapsed since timestamp of a mongodb object + reformatting timestamp显示自 mongodb 对象的时间戳 + 重新格式化时间戳以来经过的时间
【发布时间】:2017-08-17 03:01:33
【问题描述】:

我正在创建一个博客,您可以在博客中添加 cmets(显然)。在我的 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>

但是,这只是以以下格式显示日期:Fri Mar 24 2017

我想显示的是发表评论后的时间。例如:“1 min ago”、“10 mins ago”等。如何使用JS来显示?

同样,如果我想显示日期,如何重新格式化为 mm/dd/yyyy?

谢谢

更新:

这是我的 cmets 创建路由,存储在 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('');
});
});

【问题讨论】:

    标签: javascript mongodb mongoose momentjs ejs


    【解决方案1】:

    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 来显示时间前或相对时间:

    <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>
    

    记得将 moment 添加到你的 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);
            }
        }
    });
    

    【讨论】:

    • 感谢您的回复 - 看起来应该可以解决问题。我应该把矩对象放在哪里?
    • 理想情况下,您应该将发送到模板的数据注入它,就像上面的示例一样,它被发送为res.render('index', { moment: moment, blogs: blogs });
    • 您能否用代码更新您的问题,显示您如何将数据发送到您的 ejs 模板,我认为它类似于上面的示例?
    • 嘿,刚刚添加了我的 cmets (POST) 路由 + ajax
    • 太棒了!!!!这完美:) 我不知道时刻库。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 2021-12-19
    • 2019-02-17
    相关资源
    最近更新 更多