[英]How to get the last 10 messages from the mongodb?
在我的項目中有一些聊天模塊。 我需要為每 N 條消息創建請求。 如何在 frontend-node-mongo 中正確創建請求。 例如,我收到了 10 條最后一條消息並向上滾動以查看以前的消息,我如何跳過它們並獲取下 5 條消息? 現在我可以無限制地收到所有消息。
節點
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"})
}
})
使用 mongoose model,您可以使用 pipe 功能,如跳過和限制分頁。
Message.find({criteria}).skip(number_of_records_to_skip).limit(number_of_records_to_fetch)
只需根據您在 UI 上的頁面大小計算您需要跳過多少,然后通過查詢參數將其傳遞給后端。 對於 mongoose 解決方案的完整分頁,只需搜索網絡或 stackoverflow。 這是一個: Mongoose 從服務器端分頁
我想您已經在計算限制(要顯示的記錄數)和跳過(要跳過的記錄數)。
您可以簡單地使用聚合管道,如下所示。
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);
如果未指定跳過和限制,上述查詢將簡單地返回所有記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.