当在一个对象中传递多个帖子和多天时,有没有办法将createdAt从MongoDB转换成“day ago”格式?

vom3gejh  于 2022-09-21  发布在  Go
关注(0)|答案(1)|浏览(101)

我目前正在构建一个Web应用程序,有多个帖子的时间表,并想为每个帖子添加“天前”格式的日期和时间信息。

对于一篇文章,我使用“javascript-time-ago”包,通过以下方式从MongoDB转换createdAT字段:

[控制器js文件]

const TimeAgo = require('javascript-time-ago');
const en = require('javascript-time-ago/locale/en');
TimeAgo.addDefaultLocale(en)
const timeAgo = new TimeAgo('en-US')

module.exports.showPost = async (req, res,) => {
    const post = await Post.findById(req.params.id).populate({
        path: 'reviews',
        populate: {
            path: 'author'
        }
    }).populate('author');
    if (!post) {
        req.flash('error', 'Cannot find that post!');
        return res.redirect('/posts');
    }
    const user = await User.findById(post.author); 
    const created = post.createdAt;
    const createdAgo = timeAgo.format(created);

    res.render('posts/show', { post, user, imgLocation, createdAgo });
}

[查看ejs文件]

<div class="card-footer text-muted">
    posted: <%= createdAgo %>
</div>

当它只显示一个帖子时,这很有效。

然而,对于时间线,我在一个对象中传递多个帖子,并在ejs端提取它,如下所示:

[控制器js文件]

module.exports.index = async (req, res) => {
    const posts = await Post.find({}).populate().populate('author');
    const currentUser = await User.findById(req.user);
    res.render('posts/index', { posts, currentUser, imgLocation })
}

[查看ejs文件]

<% for (let post of posts){%>
    <div class="card mb-3">
        <div class="row">
           <div class="col-md-4">
               <% if(post.images.length) { %>
                   <img class="img-fluid" alt="" src="<%= post.images[0].url %>">
               <% } else { %>
                   <img class="img-fluid" alt="" 
                                src="<%= imgLocation %>">
               <% } %>
           </div>
        </div>
    </div>
<% }%>

当我在一个对象中传递多个帖子和多天时,有没有办法将createdAt从MongoDB转换为“day ago”格式?

5f0d552i

5f0d552i1#

在一些额外的试验和错误之后,我使用map()更新了我的代码,如下所示。我不确定这是不是正确的方式,但它似乎运行得很好。

[控制器js文件]

const TimeAgo = require('javascript-time-ago');
const en = require('javascript-time-ago/locale/en');
TimeAgo.addDefaultLocale(en)
const timeAgo = new TimeAgo('en-US')

module.exports.index = async (req, res) => {
    let posts = await Post.find({}).populate().populate('author');
    const currentUser = await User.findById(req.user);
    posts = posts.map(function(currentObject){
        return {
            _id: currentObject._id,
            title: currentObject.title,
            images: currentObject.images,
            description: currentObject.description,
            author: currentObject.author,
            reviews: currentObject.reviews,
            createdAt: timeAgo.format(currentObject.createdAt),
            updatedAt: currentObject.updatedAt
        }
    })
    res.render('posts/index', { posts, currentUser, imgLocation })
}

[查看ejs文件(添加)]

<p class="text-muted">
    posted: <%= post.createdAt %>
</p>

相关问题