search

Home  >  Q&A  >  body text

mongodb 用户点赞功能怎么设计比较合理?

假设用户为文章点赞,点赞操作是可以取消的。

用户和文章应该是多对多的关系,我看了一下 mongodb 官网上面的 一对多的实例,像它这样在 的一方添加 的 id,应该是比较适合那种建立了就不会轻易发生改变的关系。但像点赞这种经常发生改变的操作似乎就不太适用这种形式了。

后来我想了两个方案。
第一种是在 用户文档 中添加一个 like 的数组,每点赞一次就给把 文章id push 到 like 里面,每次删除就直接删除数组里面的 文章id 。

// User
{
  username: 'test',
  like: [123, 234, 345, 456, 567, 678, 789,890]  // 文章id
}

第二种就是用传统的 RDB 的方法,新建一个 Like 的 collection,里面存的是 用户id 和 文章id 。

// Like
{
  user_id: 111,
  post_id: 123
}

由于没有实践经验,所以特地来请教一下。顺便问下还有没有其他更好的方式?

怪我咯怪我咯2796 days ago1061

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-24 09:13:52

    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.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-24 09:13:52

    The latter option is recommended, because you should also count the number of likes for each article.

    reply
    0
  • Cancelreply