按日期对猫鼬模式数组进行分类 [英] Classify mongoose schema arrays by date

查看:38
本文介绍了按日期对猫鼬模式数组进行分类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是架构:

var userschema = new mongoose.Schema({

  user: String,
  messages: [{ 

              title: String,
              author: String,
              message: String,
              date: { type: Date, default: Date.now },

           }],

});

我正在尝试在按日期排序的单个页面中显示所有用户的消息.我知道例如如何显示特定用户的所有消息,但是如果我有多个用户,我不知道如何使用猫鼬按日期对他们的消息进行分类.有什么办法可以做到...?

I'm trying to show all the users' message in a single page ordered by date. I know how for example show all the messages of a specific user, but if I have multiple users, I don't know how to classificate their message by date using mongoose. Is there any way to do this...?

谢谢前进!

推荐答案

使用聚合框架和 $ unwind messages 数组,以便您可以 $ sort都在 date 之前

Use the aggregation framework and $unwind the messages array so that you can $sort them all by date:

Users.aggregate([
    {$unwind: '$messages'},
    {$sort: {'messages.date': 1}}
], function (err, result) {
    console.log(result);
}

这篇关于按日期对猫鼬模式数组进行分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆