我的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
这个案例有错吗?