我目前正在构建一个web应用程序,它有一个包含多个帖子的时间线,并希望为每个帖子添加日期和时间信息的“天前”格式。
对于一个使用“javascript-time”包的帖子,我执行了以下从MongoDB转换MongoDB字段的方法:
控制器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,如上面所示?
发布于 2022-09-21 04:34:18
经过更多的试验和错误之后,我使用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>https://stackoverflow.com/questions/73784557
复制相似问题