[英]Store what recipes users have liked in mongodb/flask
Creating a recipe sharing page as a school project in flask with mongodb.使用 mongodb 在 flask 中创建食谱共享页面作为学校项目。 I would like to store which recipes that users have liked so that they cannot like them more than oncew.我想存储用户喜欢的食谱,这样他们就不能再喜欢它们了。 I originally did it in session then realised you can delete or it will expire etc. Thought of storing the _id of the recipes they liked but couldnt figure out how to store many of them and look through them.我最初是在 session 中做到的,然后意识到你可以删除或者它将过期等。想存储他们喜欢的食谱的 _id,但不知道如何存储其中的许多并查看它们。 Any ideas im not thinking of here?有什么我没有想到的想法吗? Im quite new so i apologise if this is simple.我很新,所以如果这很简单,我很抱歉。 Thank you!!谢谢!!
I am also new to MongoDB.我也是 MongoDB 的新手。 How about storing recipeID
in an array field (ex: likedRecipes
), which is a part of Users
collection?将recipeID
存储在数组字段(例如: likedRecipes
)中如何,它是Users
集合的一部分? Something like below:如下所示:
Users collection:用户集合:
[
{
'user' : 1,
'likedRecipes': [
1,
4,
5
]
},
{
'user' : 2,
'likedRecipes': [
3,
4,
2
]
}
]
Recipes collection:食谱合集:
[
{
'id': 1,
'name': 'Samosa',
'ingredients': [...]
},
{
'id': 2,
'name': 'Paneer Tikka',
'ingredients': [...]
}
...,
...,
]
In the UI, when you are displaying a recipe for a user, you can make a check whether the user has already liked the recipe or not.在 UI 中,当您为用户显示食谱时,您可以检查用户是否已经喜欢该食谱。 If the user has already liked, then you can allow the user to unlike, else allow the user to like.如果用户已经点赞,则允许用户点赞,否则允许用户点赞。
Below is the query to get whether the user has liked a particular recipe or not:以下是获取用户是否喜欢特定食谱的查询:
db.user.aggregate([
{
$match: {
user: 2
}
},
{
$project: {
isLiked: {
$cond: [
{$in: [1, "$likedRecipes"]},
true,
false
]
}
}
}
])
Explanation:解释:
id
, so $match
operator is used.您需要匹配登录用户的id
,因此使用$match
运算符。$cond
is used to check whether the currently displaying recipe's id
is present in the logged in user's likedRecipe
array, if yes then return true
else return false
. $cond
用于检查当前显示的菜谱的id
是否存在于登录用户的likedRecipe
数组中,如果是则返回true
否则返回false
。$project
operator to put the above result in a new field called isLiked
.使用$project
运算符将上述结果放入名为isLiked
的新字段中。I hope it helps.我希望它有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.