mongodb - 用户收藏夹的 Mongodb 设计(优点和缺点)

标签 mongodb

我需要 2 个 API 来

1) 检索衣服列表(同时检查哪些项目是用户的最爱,并用心形标记)

2) 检索用户最喜欢的衣服列表

enter image description here

我应该如何存储用户收藏夹?

到目前为止我发现了什么:

将所有用户的 ID 嵌入到“衣服”文档中的每个衣服项目中。并在“用户”文档中保留一组用户的收藏夹。为了找出用户最喜欢的衣服,我们将利用 ID 字段在“衣服”和“用户”文档之间进行匹配。

衣服收集:

{
    "id" : "clothesID01",
    "images": [
        {"imgUrl": "https://s3-ap-1.amazonaws.com/rental/img1.png"},
        {"imgUrl": "https://s3-ap-1.amazonaws.com/rental/img2.png"},
        {"imgUrl": "https://s3-ap-1.amazonaws.com/rental/img3.png"}
    ],
    "brand" : "Halo",
    "title" : "Cheryl Dress",
    "retailPrice" : {
        "currency": "USD",
        "amount": 447 
    },
    "description":"Halo pieces are xxxx",
    "favorites" : [
        {"userId" : "user01"},
        {"userId" : "user02"}
    ],
    "isPremium" : true,
    "publishedDate" : "2019-04-04T06:12:46.839+00:00"

    ...
}

用户集合:

{
    "id": "user01",
    "phoneNumber": "+123456789",
    "favourites":[
        {"clothesId" : "clothesID01"},
        {"clothesId" : "clothesID04"}
    ]

    ...
}

基于 Rules of thumb for mongoDB Design 规则 3,

if there are more than a few thousand documents on the “many” side, don’t use an array of ObjectID references

收藏的“衣服”文档可能包含大约 10 万用户(祈祷),这可能不适合使用 ObjectID 引用数组。

对此有什么补救措施?

最佳答案

首先,你根本不需要在衣服集合中存储喜欢的数据。除了您发现的问题之外,只要两个用户同时更新对同一件衣服的喜爱,您就会遇到竞争条件。

相反,仅将用户的收藏夹存储在用户集合中,如果 ClothesID 与用户的收藏夹列表匹配,则在渲染阶段突出显示红心。

其次,使用字典 hashmap 进行更有效的查找,而不是需要搜索每个项目的列表。

 {
    "id": "user01",
    "phoneNumber": "+123456789",
    "favourites": {
       "clothesID01": true, 
       "clothesID04": true
    }
} 

当你想知道一个clothesID是否被收藏时,你可以检查是否

if (user.favourites[clothesID] === true)

这不需要遍历数组中的每一项,而是只检查内存中的一个特定位置。

因此您将使用的直接查询:

1) Retrieve a list of clothes (while checking which items are the user's favourites, and mark it with a heart shape)

const user = await db.User.findOne(ObjectId(userId));
const clothes = await db.Clothes.find(query).toArray();
for(let article of clothes) {
  if(user.favourites[article.clotheId]) {
    // display full heart
  } 
}

2) Retrieve a list of user's favourite clothes

const user = await db.User.findOne(ObjectId(userId), {favourites:true});
const favouriteIds = Object.keys(user.favourites);
const favourites = await db.Collection.find({_id: {$in: favouriteIds}}).toArray();

关于mongodb - 用户收藏夹的 Mongodb 设计(优点和缺点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55878704/

相关文章:

mongodb - 在 mongoDB 中删除数组字段大小小于 3 的文档

node.js - 使用 NodeJS 从 CSV 填充 MongoDB

java - EclipseLink MongoDB 连接

node.js - Mongoose不会更新子文档

node.js - NodeJS MongoDB Mongoose 将嵌套子文档和数组导出到 XLSX 列

mongodb - 在 vanilla GraphQL 中实现分页

mongodb - Mongo 使用(太多)太多空间

java - 通过 TLS/SSL 将 RESTHeart 连接到 MongoDB

javascript - MongoDB - 错误 : Cannot find module '../build/Release/bson'

node.js - mongodb mongoose 忽略查询中的当前用户