UCA*_*dio 5 arrays pagination mongoose mongodb node.js
我正在为 MERN 堆栈应用程序实现社交功能(关注/取消关注用户),并尝试提出一个良好的 MongoDB 解决方案,以避免潜在的大量无限关注者出现问题。具体来说,我希望避免:
从我研究的所有内容来看,似乎使用存储桶模式方法是最好的解决方案......我在这方面找到了两篇好文章: https ://www.mongodb.com/blog/post/paging-with-the-桶模式--part-1 https://www.mongodb.com/blog/post/paging-with-the-bucket-pattern--part-2
我开始像这样处理它......追随者模型:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const FollowerSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'user',
},
// creating an array of followers
followers: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'user',
},
datefol: {
type: Date,
default: Date.now,
},
},
],
count: {
type: Number,
},
createdate: {
type: Date,
default: Date.now,
required: true,
},
});
module.exports = Follower = mongoose.model('follower', FollowerSchema);
Run Code Online (Sandbox Code Playgroud)
在 Node.js api 中更新插入,将关注者添加到数组存储桶中(每个存储桶将包含 100 个关注者):
const follow = await Follower.updateOne(
{ user: req.params.id, count: { $lt: 100 } },
{
$push: {
followers: {
user: req.user.id,
datefol: Date.now(),
},
},
$inc: { count: 1 },
$setOnInsert: { user: req.params.id, createdate: Date.now() },
},
{ upsert: true }
);
Run Code Online (Sandbox Code Playgroud)
基本上每次添加关注者时,都会将其添加到找到的第一个包含少于 100 个关注者的存储桶(按计数跟踪)。
这是处理潜在大型数组的最佳方法吗?我的担忧是:
水桶图案与您所暴露的案例并不完美匹配。
最适合您需求的模式是异常值模式https://www.mongodb.com/blog/post/building-with-patterns-the-outlier-pattern
您的案例实际上与本文中的示例相同。