我正在使用 NodeJS 中的 mongoose 試驗 mongodb。我有一個簡單的網路,用戶可以在其中創建帖子。創建時,此帖子將保存到 mongodb。
在網路上,我有一個滾動事件偵聽器,它檢查用戶是否在頁面底部。如果他在底部,它將向后端進行抓取以獲取更多帖子。
我希望這些從最新到最舊的資料庫中檢索,但是貓鼬的 model.save() 方法總是在集合的末尾插入一個新模型。
因此,當創建新帖子時,后端會立即執行此操作:
const post = new Post({
text: req.body.text,
author: {
userid: user._id,
name: user.username,
picPath: user.picPath
},
images: images
});
post.save(function (err) {
let status = true;
let message = "Post mentve."
if (err) { status = false; message = err; console.log(err) }
return res.send({ status: status, msg: message });
})
這樣,一個新帖子就會被推送到收藏夾中。并且不是一成不變的。
當客戶想要新帖子時,后端會這樣做:
app.get('/dynamicPostLoad/:offset/:limit', async (req, res) => {
let offset = req.params.offset;
let limit = req.params.limit;
let response = {
status: true,
posts : [],
message: "Fetched"
};
await Post.find({}).skip(offset).limit(limit).then(products => {
response.posts = products;
}).catch((err)=> {
response.status = false;
response.message = err;
});
return res.send(response);
});
所以貓鼬會從最舊的到最新的,因為所有新的都插入到集合的末尾。
這樣,用戶將首先看到最舊的帖子,當他滾動時,會看到最舊和最舊的帖子。
我在想三個方面。
該Post.find({})
方法應該從集合末尾抓取檔案,或者該Post.save()
方法應該取消移動檔案而不是推送,或者我可以找到集合中的所有帖子并將它們反轉。(最后一個會非常緩慢)
編輯:每個帖子都包含一個創建日期,因此可以對其進行排序。
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
我用排序解決了。(仍然不明白為什么我不能將檔案插入到集合的開頭)
這是我的解決方案:
app.get('/dynamicPostLoad/:offset/:limit', async (req, res) => {
let offset = req.params.offset;
let limit = req.params.limit;
let response = {
status: true,
posts : [],
message: "Fetched"
};
// Sort every find by created date before limiting.
await Post.find({}).sort({created: -1}).skip(offset).limit(limit).then(products => {
response.posts = products;
}).catch((err)=> {
response.status = false;
response.message = err;
});
return res.send(response);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/503999.html