用Mongoose排列数组字段

我试图通过ts (timestamp)来订购下一个型号:

 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(); }; 

但是,而不是sorting我的通知,我想我sorting用户返回我的查询所有的通知。

有什么办法可以为给定的用户,通知?

感谢@JohnnyHK在这里,我留下了我的问题的答案:

 Schema.findByIdAndUpdate(user_id, { $push: { notifications: { "$each": [{ story: { parent: mongoose.Types.ObjectId(video_bookmarked), video_id: mongoose.Types.ObjectId(video_id), }, type: 'respond-video' }], "$sort": { ts: -1 } } }, $inc: { count_notifications: 1 } }).exec(); 

在你的填充内,你想sorting你可以

 .populate({ path: 'theoneyouwanttosort', options: { sort: { createdAt: -1 } } }) 

希望能帮助你:)