数组对象对猫鼬进行排序

时间:2019-07-17 13:33:20

标签: arrays node.js mongoose

我很难对一组对象进行排序,是的,我花了几天的时间在周围搜寻,但是没有运气。 我最终想要的是可以动态添加新博客,它们显示在顶部,而不是显示在底部。

我已经尝试过换档。

我尝试将时间戳记添加到所有对象,以便可以使用它按日期时间戳记进行排序。

&全部无效,我似乎无法将新内容推到顶部。

这是一个博客,它不是网站的主要功能,因为我已经在博客页面的旁边元素中添加了它。

我试图解决的问题:

我已向Schema添加时间戳,该时间戳正在使用robo 3T检查;

const postsSchema = {

title:字符串,

字幕:字符串,

内容:字符串,

时间:{

type : Date,

default: Date.now

}

};

尝试在我的Blog上进行排序以获取路线:

app.get(“ / blog”,function(req,res){

Post.find({},function(err,posts){

res.render("blog", {

  mainContent: homeStartingContent,

  posts: posts

});

posts.sort(function(a, b) {

  a = new Date(a.time);

  b = new Date(b.time);

  return a>b ? -1 : a<b ? 1 : 0;

});

});

// posts.find()。sort({日期:-1}); /////////////////////////

});

尝试对我的帖子路线进行排序,以动态撰写仅在身份验证后才能访问的新帖子:

app.post(“ / compose”,(req,res)=> {

console.log(“ req.body.time”);

if(req.isAuthenticated()){

const post = new Post({

  title: req.body.postTitle,

  subtitle: req.body.postSub,

  content: req.body.postContent,

});

post.save(function(err) {

  if (!err) {

    return res.redirect("/blog");

  }

});

}其他{

res.redirect('/login');

}

});

还有一个我没有碰过的“ compose”获取路线,对它进行排序,这有什么用吗?

app.get(“ / compose”,(req,res)=> {

if(req.isAuthenticated()){

res.render('compose');

}其他{

res.redirect('/login');

}

});

这是ejs模板中的side元素:

<aside class="col-md-4 blog-sidebar">

  <div class="p-4">

    <h2 class="font-italic">Connect</h2>

    <ol class="list-unstyled">

      <li><a href="https://www.linkedin.com/in/xxxxxxxxxxxxxxxxxx/">LinkedIn</a></li>

      <li><a href="#">Github</a></li>

    </ol>

  </div>

  <div class="p-4">

    <h2 class="font-italic">Posts</h2>

      <%  posts.forEach(function(post){ %>

        <h3><%=post.title%></h3>

        <h4><%=post.subtitle%></h4>

        <p><%=post.content.substring(0, 50) + " ..."%>

        <a href="/posts/<%=post._id%>">++</a>

        </p>

        <% }) %>

  </div>

</aside><!-- /.blog-sidebar -->

阵列没有响应。感觉应该很快解决!

0 个答案:

没有答案