假設(shè)用戶為文章點(diǎn)贊,點(diǎn)贊操作是可以取消的。
用戶和文章應(yīng)該是多對(duì)多的關(guān)系,我看了一下 mongodb 官網(wǎng)上面的 一對(duì)多的實(shí)例,像它這樣在 多 的一方添加 一 的 id,應(yīng)該是比較適合那種建立了就不會(huì)輕易發(fā)生改變的關(guān)系。但像點(diǎn)贊這種經(jīng)常發(fā)生改變的操作似乎就不太適用這種形式了。
后來(lái)我想了兩個(gè)方案。
第一種是在 用戶文檔 中添加一個(gè) like
的數(shù)組,每點(diǎn)贊一次就給把 文章id push 到 like
里面,每次刪除就直接刪除數(shù)組里面的 文章id 。
// User
{
username: 'test',
like: [123, 234, 345, 456, 567, 678, 789,890] // 文章id
}
第二種就是用傳統(tǒng)的 RDB 的方法,新建一個(gè) Like
的 collection,里面存的是 用戶id 和 文章id 。
// Like
{
user_id: 111,
post_id: 123
}
由于沒(méi)有實(shí)踐經(jīng)驗(yàn),所以特地來(lái)請(qǐng)教一下。順便問(wèn)下還有沒(méi)有其他更好的方式?
走同樣的路,發(fā)現(xiàn)不同的人生
A third solution is proposed here, which is to store an array of _ids of users who liked the article in the posts collection, for example:
// posts
{
_id: ObjectID('4e7020cb7cac81af7136236b'),
users_like_this_post: [
ObjectID('4e7020cb7cac81af71362361'),
ObjectID('4e7020cb7cac81af71362362')
]
}
Check the users who liked an article:
post = db.posts.findOne({_id: ObjectID('4e7020cb7cac81af7136236b')});
console.log(post.users_like_this_post);
Check the number of likes for an article:
post = db.posts.findOne({_id: ObjectID('4e7020cb7cac81af7136236b')});
console.log(post.users_like_this_post.length);
Check articles with 100 likes:
posts = db.posts.find({'users_like_this_post.100': {$exists: true}});
Check articles liked by user:
posts = db.posts.find({users_like_this_post: user._id});
user liked the post:
db.posts.update({_id: post._id}, {$addToSet: {users_like_this_post: user._id}});
user unlikes the post:
db.posts.update({_id: post._id}, {$pull: {users_like_this_post: user._id}});
PS: The above code has not been tested, please refer to the documentation for testing.
The latter option is recommended, because you should also count the number of likes for each article.