我需要 2 个 API
1)检索衣服列表(同时检查哪些项目是用户最喜欢的,并用心形标记)
2) 检索用户最喜欢的衣服列表
我应该如何存储用户收藏夹?
到目前为止我想出了什么:
将所有用户的 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"
...
}
Run Code Online (Sandbox Code Playgroud)
用户集合:
{
"id": "user01",
"phoneNumber": "+123456789",
"favourites":[
{"clothesId" : "clothesID01"},
{"clothesId" : "clothesID04"}
]
...
}
Run Code Online (Sandbox Code Playgroud)
基于mongoDB 设计的经验法则,在规则 3 中,
如果“多”端有超过几千个文档,请不要使用 ObjectID 引用数组
“衣服”文档收藏夹可能包含大约 10 万个用户(手指交叉),这可能不适合使用 ObjectID 引用数组。
对此有什么补救措施?
首先,您根本不需要将喜欢的数据存储在衣服集合中。除了您发现的问题之外,每当两个用户同时更新最喜欢的同一服装项目时,您就会遇到竞争条件。
相反,只将用户的收藏夹存储在 User 集合中,然后在渲染阶段突出显示红心,如果 ClothesID 与用户的收藏夹列表匹配。
其次,使用字典哈希图进行更多的执行查找,而不是需要搜索每个项目的列表。
{
"id": "user01",
"phoneNumber": "+123456789",
"favourites": {
"clothesID01": true,
"clothesID04": true
}
}
Run Code Online (Sandbox Code Playgroud)
当您想知道某个衣服 ID 是否被收藏时,您可以检查是否
if (user.favourites[clothesID] === true)
这不需要迭代数组中的每一项,而是只检查内存中的一个特定位置。
因此,您将使用的直接查询:
1)检索衣服列表(同时检查哪些项目是用户最喜欢的,并用心形标记)
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
}
}
Run Code Online (Sandbox Code Playgroud)
2) 检索用户最喜欢的衣服列表
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();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1170 次 |
最近记录: |