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

时间:2016-09-02 05:46:49

标签: mongodb sorting mongoose mongodb-query mongoose-populate

我的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);

我想基于desc顺序的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使用1'desc'asc'还是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的一个错误。

请跟踪this issue on GitHub

UPDATE2: 它说没有支持。但我不知道为什么......在sort populate中使用String s; for( int i = 0; i < 10; i++) { s = ""; for( int j = 0; j <= i; j++) s+= "X"; for( int j = i+1; j < 10; j++) s+= "O"; System.out.println(s); } 是否有错?

2 个答案:

答案 0 :(得分:0)

试试这个..

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

答案 1 :(得分:0)

文档(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
    })