首页 > 解决方案 > 在 MongoDB 中设计追随者和追随者模式?

问题描述

我想为类似于instagramfollowers的社交媒体应用程序设计和模块。followee(following)

我已经为相同的方法实施了以下方法

用户架构

module.exports = mongoose.model('users', new Schema({
    name: { type: String, default: null },
    gender: { type: String, default: null, enum: ['male', 'female', 'others', null] },
    email: { type: String, unique: true, sparse: true },
    isBlocked: { type: Boolean, default: false },
    isDeleted: { type: Boolean, default: false },
    profileImage: { type: String, default: null },
    isVerified: { type: Boolean, default: false },
}, {
    versionKey: false,
    timestamps: true
}));

追随者模式

module.exports = mongoose.model('followers', new Schema({
    followeeId: { type: ObjectId, required: true },
    followerId: { type: ObjectId, required: true }
}, {
    versionKey: false,
    timestamps: true
}));

使用此方法时,如果一个用户有 100 万关注者,则将为该用户创建 100 万条记录,如果用户关注所有关注者,则计数将为 200 万

所以平均而言:

user#1 has 1 million followers/followees = 1 million records // total records: 1 Million
user#2 has 1 million followers/followees = 1 million records // total records: 2 Million
.
.
user#1000 has 1 million followers/followees = 1 million records // total records: 1 Billion
.
.
user#1,000,000 has 1 million followers/followees = 1 million records // total records: 1 Trillion

如果我使用这种方法,一个集合中将有超过数万亿条记录

那么生成这样的记录可以吗?

或者请建议是否有任何不同的方法来设计这个模式

标签: mongodbdatabase-designdatabase-schema

解决方案


在你自己的代码中找到缺陷的工作做得很好。根据您的架构,它会创建太多记录,但是在查找用户的关注者时查询数据库还有另一个问题,它会有点慢,您还必须进行单独的查询!

所以必须有另一种方式。还有一件事,用大写字母命名模型始终是最佳实践。

这就是我对同样问题的处理方式。

module.exports = mongoose.model('User', new Schema({
    name: { type: String, default: null },
    gender: { type: String, default: null, enum: ['male', 'female', 'others', null] },
    email: { type: String, unique: true, sparse: true },
    isBlocked: { type: Boolean, default: false },
    isDeleted: { type: Boolean, default: false },
    profileImage: { type: String, default: null },
    isVerified: { type: Boolean, default: false },
    followers: [{type: ObjectId, ref: "User", required: true}],
    following: [{type: ObjectId, ref: "User", required: true}]
}, {
    versionKey: false,
    timestamps: true
}));

我会添加“关注者”和“关注者”字段,其中包含不同用户的 ObjectId 数组。因此,每次有人关注用户时,您都会更新两个用户的记录 - 将关注者添加到关注者用户的关注字段,反之亦然。

这种方法需要在有人关注某人时执行两次数据库更新查询。但它会节省大量资源和稍后查询的时间(您不需要为此进行单独的查询)。

如果您也发现这种方法有任何错误,请告诉我。


推荐阅读