问题
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?
回答1:
The documentation (http://mongoosejs.com/docs/api.html#document_Document-populate) states something like:
Chat.find().populate({
path: 'lastMessage'
, select: 'timestamp'
, options: { sort: { timestamp: -1 }}
}).exec(function (err, chats) {
//do something
})
If this is not working first check it with for example text, to see if it's a datetime sort issue
UPDATE: When i re-read your question i noticed the issue, you want to sort all messages based on the last message timestamp. There is no need to sort in the population because it only returns 1 item (there is no array of last messages).
So the syntax would be:
Chat.find().populate({
path: 'lastMessage'
, select: 'timestamp'})
.sort('lastMessage.timestamp')
.exec(function (err, chats) {
//do something
})
回答2:
Try this..
ChatModel
.find({})
.populate('lastMessage', 'timestamp', {
options: {
sort: {
'lastMessage.timestamp': 'desc'
}
}
})
.exec()
.then(chats => console.log('chats', chats))
来源:https://stackoverflow.com/questions/39285102/sort-in-populate-does-not-work-mongoose