在猫鼬中排序子文档

乔什·斯莱特(Josh Slate)

我正在尝试按日期排序来自Mongoose的输出,该日期存储在子文档中。我相信可以在客户端更轻松地完成此操作,但是我想限制服务器资源的使用并延迟加载子文档,而不是立即加载所有子文档。

我正在使用私人消息传递功能。我有一个称为“对话”的模式,并且有另一个称为“消息”的模式。他们的代码如下:

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(这是一个缓慢且文献不完善的ORM),即可通过嵌套属性对对象数组进行排序。穿上您的超赞裤子,滚动自己的排序功能,然后将其命名为“ day”。

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的详细信息

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章