在填充中排序不起作用(猫鼬)
我的MongoDB版本3.2,猫鼬版本是4.6.0
My MongoDB version 3.2, mongoose version is 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的时间戳进行排序.我尝试了这三个
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))
此外,无论我对timestamp
使用-1
还是1
,'desc'
或'asc'
,它总是给我相同的结果:
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:
好像是猫鼬的虫子.
请在GitHub上跟踪此问题.
Please track this issue on GitHub.
UPDATE2:
它说不支持.但是我不知道为什么...在这种情况下在populate
中使用sort
是错误的吗?
UPDATE2:
It said not supported. But I don't know why... Is using sort
in populate
wrong for this case?
文档( http ://mongoosejs.com/docs/api.html#document_Document-populate )表示类似以下内容:
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
更新: 当我重新阅读您的问题时,我注意到了这个问题,您想根据上一个消息时间戳对所有消息进行排序.无需对总体进行排序,因为它仅返回1个项目(没有最后一条消息的数组).
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).
因此语法为:
Chat.find().populate({
path: 'lastMessage'
, select: 'timestamp'})
.sort('lastMessage.timestamp')
.exec(function (err, chats) {
//do something
})