填充中的排序不起作用(猫鼬)

2023-12-24

我的MongoDB版本是3.2,mongoose版本是4.6.0

这些是我的架构:

// chat
const chatSchema = new mongoose.Schema({
  users: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }],
  lastMessage:  { type: mongoose.Schema.Types.ObjectId, ref: 'Message' }
});
export const ChatModel = mongoose.model('Chat', chatSchema);

// message
const messageSchema = new mongoose.Schema({
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
  chat: { type: mongoose.Schema.Types.ObjectId, ref: 'Chat', required: true },
  text: { type: String, required: true },
  timestamp: { type: Date, default: Date.now }
});
export const MessageModel = mongoose.model('Message', messageSchema);

我想根据 lastMessage 的时间戳按降序排序。我尝试了这三个

ChatModel
  .find({}, 'lastMessage')
  .populate('lastMessage', 'timestamp', null, { sort: { timestamp: -1 }})
  .exec()
  .then(chats => console.log(chats))

ChatModel
  .find({}, 'lastMessage')
  .populate({
    path: 'lastMessage',
    select: 'timestamp',
    options: { sort: { timestamp: -1 }}
  })
  .exec()
  .then(chats => console.log(chats))

ChatModel
  .find({}, 'lastMessage')
  .populate('lastMessage', 'timestamp')
  .sort({ 'lastMessage.timestamp': -1 })
  .exec()
  .then(chats => console.log(chats))

另外,无论我使用-1 or 1, 'desc', or 'asc' for timestamp,它总是给我相同的结果:

  [{
    _id: 57c8a682cde8baf5c36eb1fc,
    lastMessage: {
      _id: 57c8baa29a293eace7f9be15,
      timestamp: 2016-09-01T23:32:50.344Z
    }
  }, {
    _id: 57c8a6d0cde8baf5c36eb1fe,
    lastMessage: {
      _id: 57c8fabb4362b3c25d828774,
      timestamp: 2016-09-02T04:06:19.421Z
    }
  }]

可能是什么原因造成的?谢谢


UPDATE1:

看起来像是 Mongoose 的 bug。

请追踪这个问题在 GitHub 上 https://github.com/Automattic/mongoose/issues/4481.


更新2: 据说不支持。但我不知道为什么...正在使用sort in populate这个案例有错吗?


文档(http://mongoosejs.com/docs/api.html#document_Document-populate http://mongoosejs.com/docs/api.html#document_Document-populate) 声明如下:

Chat.find().populate({
    path: 'lastMessage'
  , select: 'timestamp'
  , options: { sort: { timestamp: -1 }}
}).exec(function (err, chats) {
  //do something
})

如果这不起作用,请首先使用示例文本进行检查,看看是否是日期时间排序问题

更新: 当我重新阅读您的问题时,我注意到了这个问题,您想根据最后一条消息时间戳对所有消息进行排序。不需要对总体进行排序,因为它只返回 1 项(没有最后消息的数组)。

所以语法是:

Chat.find().populate({
        path: 'lastMessage'
      , select: 'timestamp'})
.sort('lastMessage.timestamp')
.exec(function (err, chats) {
      //do something
    })
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

填充中的排序不起作用(猫鼬) 的相关文章

随机推荐