按日期对猫鼬模式数组进行分类
问题描述:
这是架构:
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);
}