【发布时间】:2016-12-11 00:34:54
【问题描述】:
我正在尝试通过ts(时间戳)订购下一个型号:
var Schema = new mongoose.Schema({
info: {
name: { type: String, trim: true, validate: [
{ validator: validations.user.maxName, msg: 'The name must be shorter' }
]}
},
gender: { type: String, trim: true, enum: ['Male', 'Female'] },
notifications: [{
story: {
_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Story' },
video_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Video' }
},
video: {
_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Video' },
video_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Video' }
},
type: { type: String },
read: { type: Number, default: 0 }, // 0 - Unread, 1 - read
ts: { type: Date, default: Date.now }
}]
}, { timestamps: { createdAt: 'created_at' } });
这是我为了订购这些通知元素而尝试使用的代码,如下所示:
UserSchema.statics.getNotifications = function (user_id) {
return this.findById(user_id)
.select('notifications')
.populate({
path: 'notifications.story.video_id',
select: '_id user story',
populate: ([{
path: 'user',
select: '_id nickname info.thumbnail'
}, {
path: 'story',
select: 'title'
}])
})
.populate({
path: 'notifications.video.video_id',
select: '_id user story parent',
populate: ([{
path: 'user',
select: '_id nickname'
}, {
path: 'story',
select: '_id'
}])
})
.sort({ 'notifications.ts': -1 })
.exec();
};
但我想我不是对我的通知进行排序,而是对返回我的查询以及所有通知的用户进行排序。
有没有办法为给定的用户排序通知?
【问题讨论】:
-
无法使用
find对数组字段进行排序,通常最好保持数组排序,因为它使用$push和$sort修饰符进行更新。 -
我会用最终结果更新我的问题。这真的帮助了@JohnnyHK,谢谢!。