【问题标题】:Sort array field with Mongoose使用 Mongoose 对数组字段进行排序
【发布时间】: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,谢谢!。

标签: node.js mongodb mongoose


【解决方案1】:

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

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

希望能帮到你:)

【讨论】:

  • 不幸的是,这无济于事,因为 OP 尝试排序的 notifications 字段不是正在填充的字段(它是元素 的各个字段正在填充的数组)。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 2012-10-02
    • 2012-12-17
    • 2014-10-01
    • 2016-09-15
    相关资源
    最近更新 更多