首页 > 解决方案 > 用于保存用户联系人的 MongoDB Schema 优化

问题描述

我想设计一个存储用户联系人的架构。

这是我现有的模式:

用户模式

_id : ObjectId("5c53653451154c6da4623a77"),
name : “something”,
email : “something”,
password : “something”,

配置文件架构

"_id" : ObjectId("5c53653451154c6da4623a88"),
user_id - ref
mobile : “something”,
company” : “something”,
designation : “something”,
website : “something”,
social: {
    youtube: {
        type: String
    },
    twitter: {
        type: String
    },
    facebook: {
        type: String
    },
    linkedin: {
        type: String
    },
    instagram: {
        type: String
    }
}

我可以想到接触模式的两种方法,但都有一些缺点:

第一种方法

"_id" : ObjectId("5c53653451154c6da4623a99"),
user_id - ref,
"contacts": [
   {
    name : “something”,
    company : “something”,
    designation : “something”,
    website : “something”,
    social: { something },
    mobile : “something”
   },
   {
    name : “something”,
    company : “something”,
    designation : “something”,
    website : “something”,
    social: { something },
    mobile : “something”
    },
    ...
]

上述结构的问题在于,当用户更新他们的个人资料时,联系人字段无法获得更新的值。但是在这种方法中,很容易查询和检索特定用户的所有联系人并将响应发回。

第二种方法

"_id" : ObjectId("5c53653451154c6da4623a99"),
user_id : ref,
contacts: [
    profile_id,
    profile_id,
    profile_id,
    profile_id,
    profile_id,
    profile_id,
    ...
]

在此结构中,当用户更新其个人资料时,联系人具有更新的用户值。但是这里的问题是在查询时我必须从 Contact 模式中获取配置文件 id,然后查询 Profile 模式并将值作为响应返回给客户端。

当有 30K-50K 联系人时会发生什么 - 我需要查询数据库 50K 次吗?还是有更好的方法?

在 node.js 上构建,使用猫鼬。

标签: javascriptnode.jsmongodbmongoose-schema

解决方案


基本上你有一个需要关系数据库的场景。但是您也可以在mongo中实现这一点。

你需要使用猫鼬的填充。用你的第二种方法。您存储个人资料 ID 的位置。

User.find({_id: '5c53653451154c6da4623a77'}).populate({
path:'profiles',
options: {
    limit: 10,
    skip: 0
}}).exec();

猫鼬居住

此查询将返回相关配置文件。如果你有 50K 这样的数据。您必须限制一个请求中的数据。

注意:每个文档的 Mongodb 限制为 16mb。存储这么多数据是不可能的。

因此,只需重新考虑您的数据库。


推荐阅读