简体   繁体   English

如何从 mongodb 获取最后 10 条消息?

[英]How to get the last 10 messages from the mongodb?

In my project has some chat module.在我的项目中有一些聊天模块。 I need to create request for every N messages.我需要为每 N 条消息创建请求。 How correctly create request in frontend-node-mongo.如何在 frontend-node-mongo 中正确创建请求。 For example I got 10 last messages and scroll up for watching previous messages, how can I skip them and get next 5 messages?例如,我收到了 10 条最后一条消息并向上滚动以查看以前的消息,我如何跳过它们并获取下 5 条消息? Now I get all messages without limit.现在我可以无限制地收到所有消息。

Node节点

router.get(
  '/messages',
  async (req, res) => {
    try {
      const {user, destination} = req.query
      let userFrom = await User.findOne({email: user})
      let userTo = await User.findOne({email: destination})
      let messages = await Message.find({
        $or: [{senderId: userFrom, recipientId: userTo}, {senderId: userTo, recipientId: userFrom}]
      })
      return messages ? res.status(200).json(messages) : res.status(204)
    } catch (e) {
      res.status(500).json({message: "Error"})
    }
  })

With mongoose model, you can use pipe functions like skip and limit for pagination.使用 mongoose model,您可以使用 pipe 功能,如跳过和限制分页。

Message.find({criteria}).skip(number_of_records_to_skip).limit(number_of_records_to_fetch)

Just calculate, based on your page size on UI, how much you need to skip, and pass this via query parameter to the backend.只需根据您在 UI 上的页面大小计算您需要跳过多少,然后通过查询参数将其传递给后端。 And for complete pagination with mongoose solution just search the net or stackoverflow.对于 mongoose 解决方案的完整分页,只需搜索网络或 stackoverflow。 Here is one: Mongoose pagination from server side这是一个: Mongoose 从服务器端分页

I suppose you are already calculating the limit (Number of records to display) and skip (Number of records to skip).我想您已经在计算限制(要显示的记录数)和跳过(要跳过的记录数)。

You can simply use the aggregate pipeline as below.您可以简单地使用聚合管道,如下所示。

let aggregatePipelines = [
    {
        $match: {
            $or: [
                {
                    senderId: userFrom,
                    recipientId: userTo
                },
                {
                    senderId: userTo,
                    recipientId: userFrom
                }
            ]
        }
    }
]

if (skip != 0)
    aggregatePipline.push({ $skip: skip });

if (pageLimit != 0)
    aggregatePipline.push({ $limit: pageLimit });

let messages = await Message.aggregate(aggregatePipelines);

The above query will simply return all the records if skip and limit are not specified.如果未指定跳过和限制,上述查询将简单地返回所有记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM