使用Mongoose

时间:2016-12-10 14:11:46

标签: node.js mongodb mongoose

我试图按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();
};

但是我没有对通知进行排序,而是在对使用所有通知返回查询的用户进行排序。

有没有办法为给定用户排序通知?

2 个答案:

答案 0 :(得分:3)

感谢@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();

答案 1 :(得分:1)

在你的填充内你想要排序,你可以

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

希望能帮助你:)