I'm trying to order the next model by 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' } });
This is the code I'm trying to use in order to order these notification elements is what it follows:
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();
};
But instead of sorting my notifications, I guess I'm sorting the users that return my query with all the notifications.
Is there any way to sort for a given user, the notifications?
find, it's typically better to keep the array sorted as it's updated using$pushwith the$sortmodifier.