【问题标题】:Design Followers and Followees Schema in MongoDB?在 MongoDB 中设计追随者和追随者模式?
【发布时间】:2021-11-25 21:52:10
【问题描述】:

我想为类似于 instagram 的社交媒体应用程序设计 followersfollowee(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

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

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

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

【问题讨论】:

    标签: mongodb database-design database-schema


    【解决方案1】:

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

    所以必须有另一种方式。还有一件事,最好用大写字母命名模型。

    对于同样的问题,我会这样做。

    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 数组。因此,每次有人关注用户时,您都会更新两个用户的记录 - 将关注者添加到关注者用户的关注字段,反之亦然。

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

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

    【讨论】:

    • 我想到了你提到的这个方法......但是 ObjectId 的大小是 12 字节,每个文档的限制是 16 MB。因此,经过计算,我们可以存储大约 140 万个 ObjectId(700,000 个关注者和 700,000 个关注者),并且关注者可以轻松超过 200 万大关。
    猜你喜欢
    • 2021-10-09
    • 1970-01-01
    • 2021-10-23
    • 2019-07-03
    • 1970-01-01
    • 2021-06-13
    • 2017-12-08
    • 2021-02-18
    • 2011-09-07
    相关资源
    最近更新 更多