sortingMongoose中的一个子文档

我正试图sorting来自Mongoose的输出存储在一个子文档中的date。 我相信这可以在客户端更容易完成,但是我想限制在服务器资源上的延迟,并延迟加载子文档,而不是一次加载所有子文档。

我正在开发一个私人消息function。 我有一个名为Conversations定义的架构,我有另一个称为消息定义的架构。 他们的代码如下:

const mongoose = require('mongoose'); const ChatSchema = new mongoose.Schema({ messageBody: { type: String, required: true }, from: { type: String, required: true } }, { timestamps: true // Saves createdAt and updatedAt as dates. createdAt will be our timestamp. }); const ConversationSchema = new mongoose.Schema({ participants: [String], messages: [ChatSchema] }); module.exports = mongoose.model('Chat', ChatSchema); module.exports = mongoose.model('Conversation', ConversationSchema); 

信息保存得很好,信息似乎正确地存储在数据库中。 当我尝试使用cursor.sort()方法返回最近的消息时,我的问题来了。 查询(后面的代码)返回一个消息,但我不能得到它返回最新的消息。

 exports.getConversations = function(req, res, next) { // Only return one message from each conversation to display as snippet Conversation.find({ participants: req.user._id }) .sort('-messages.createdAt') .slice('messages', 1).exec(function(err, conversations) { if (err) { res.send({ error: err }); return next(err); } // other code... 

我已经尝试了每一个我在这篇文章中发现的变化无济于事: https : //stackoverflow.com/a/15081087/5956144

你不需要用一个ORM(一个缓慢而且logging不完整的)来用一个嵌套属性对一个对象数组进行sorting。 穿上你真棒裤子,推出你自己的sortingfunction,并且每天给它打电话。

 function byMessageCreatedAt(a, b){ //modify the below comparison however you need to to compare two times return a.messages.createdAt - b.messages.createdAt } var results = conversation.find({blah}).sort(byMessageCreatedAt); 

在JavaScript中sorting的细节在这里find