[英]Sort array field with 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();
};
但是,我想不是對通知進行排序,而是對對所有通知返回查詢的用戶進行排序。
有沒有辦法為給定的用戶排序通知?
感謝@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();
在您要填充的內部,您可以
.populate({ path: 'theoneyouwanttosort', options: { sort: { createdAt: -1 } } })
希望能對您有所幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.