从集合中获取最后 N 个条目 |使用 Mongoose 的分页问题

我已经制作了通知集合,并按照以下架构在其中放置了通知:

Give it a try,All the best (yes)

我试图通过分页和排序来显示通知,但我得到了一个特定的顺序。 比如前 N 个通知将指向 1 小时前到 2 天前,然后另一个分页将再次显示 5 小时前到 26 天前,依此类推。

我使用这个查询来查找:

{
  userid: mongoose.Schema.Types.ObjectId  // the user who generated this notification
  customReceivers: [String],time: Number,// new Date().getTime();
... other fields
}
notificationmodel.find({userid: {$in: followingList}}.sort({time: -1}).skip(pageNo * entriesPerPage).limit(entriesPerPage).then(...

我试过用 followingList = [mongoose.ObjectId("60bb75c3eb840300226bd3a8"),mongoose.ObjectId("60bb77eeeb840300226bd3ac"),...] 没用

默认情况下,条目按时间升序保存,我只需要取最后 N 个条目并反转数组。但我得到的顺序是不同的。感谢帮助

b_bunny 回答:从集合中获取最后 N 个条目 |使用 Mongoose 的分页问题

如果通过 time 属性排序不起作用,也许通过 _id 排序会有所帮助。

notificationModel.find({userid: {$in: followingList}}.sort({_id: -1}).skip(pageNo * entriesPerPage).limit(entriesPerPage).then(...
,

找到了解决方案。问题出在声明中:

notificationModel.find({userid: {$in: followingList}}.sort({time: -1}).skip(pageNo * entryPerPage).limit(entriesPerPage).then(. ..

$in 不保证数据的顺序(无论是 1 对 1 还是 1 对多关系),因此需要通过使用 $cond 和 $eq 或我所做的条件检查它:

  1. 获取用户关注的人创建的所有通知 ID
  2. 获取详细信息和标志,如 seenByUser 或任何其他汇总的详细信息,并放弃跳过和限制的条件
notifications = await notificationModel.aggregate([
            {
                $match: { _id: { $in: notificationIDs } },// Id got from find() previously
                
            },{$sort: {"time": -1}},{ $skip: (pageNo - 1) * entriesPerPage },{ $limit: entriesPerPage },}
本文链接:https://www.f2er.com/1068.html

大家都在问