My MongoDB version 3.2, mongoose version is 4.6.0
These are my schemas:
// 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);
I want to sort based on lastMessage's timestamp in a desc order. I tried these three
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))
Also, no matter I use -1
or 1
, 'desc'
, or 'asc'
for timestamp
, it always gives me same results:
[{
_id: 57c8a682cde8baf5c36eb1fc,
lastMessage: {
_id: 57c8baa29a293eace7f9be15,
timestamp: 2016-09-01T23:32:50.344Z
}
}, {
_id: 57c8a6d0cde8baf5c36eb1fe,
lastMessage: {
_id: 57c8fabb4362b3c25d828774,
timestamp: 2016-09-02T04:06:19.421Z
}
}]
What may cause this? Thanks
UPDATE1:
It seems like a bug of Mongoose.
Please track this issue on GitHub.
UPDATE2:
It said not supported. But I don't know why... Is using sort
in populate
wrong for this case?