Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array field with Mongoose

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?

like image 391
DevStarlight Avatar asked Sep 24 '26 05:09

DevStarlight


2 Answers

Inside your populate you want to sort you can

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

Hope that can help you :)

like image 157
EQuimper Avatar answered Sep 27 '26 01:09

EQuimper


Thanks to @JohnnyHK here bellow I leave the answer of my question:

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();
like image 32
DevStarlight Avatar answered Sep 27 '26 02:09

DevStarlight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!