存储/获取从Mongo/RectiveMongo中的列表引用的值的最佳方法? [英] Best way to store/get values referenced from a list in Mongo/RectiveMongo?

查看:86
本文介绍了存储/获取从Mongo/RectiveMongo中的列表引用的值的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常普遍的用例-评论列表.每个评论都有一个作者.

I have a quite common use case - a list of comments. Each comment has an author.

由于作者可以发表多条评论,因此我使用引用将评论的引用存储到作者.

I'm storing the reference from a comment to the author using a reference, since an author can make multiple comments.

现在,我正在使用ReactiveMongo,并希望尝试保持数据库访问异步,但是在这种情况下,我不知道如何.我对数据库进行异步访问,以获取评论,但是对于每个评论,我都必须获得作者,直到现在,我知道的唯一方法是遍历评论并同步获取用户:

Now I'm working with ReactiveMongo and want to try to keep the database access asynchronous, but in this case, I don't know how. I do an asynchronous access to the database, to get the comments, but then for each comment I have to get the author, and until now the only way I know is to loop through the comments and get the user synchronously:

val userOption:Option[JsObject] = Await.result(usersCollection.find(Json.obj("id" -> userId).one[JsObject], timeout)
//...

除此之外,我可以:

  • 异步获取每个用户,但随后我必须引入一些功能,直到所有用户都被提取为止,以便返回响应,并且我的代码很可能变得一团糟.

  • Get each user asynchronously but then I have to introduce some functionality to wait until all user were fetched, in order to return the response, and my code is likely to become a mess.

存储完整的用户对象-至少在每个注释中我需要注释(图片,名称等).由于每次用户更改某些内容(与注释中存储的数据有关)时,这种冗余可能会变得很麻烦,因为我将不得不遍历数据库中的所有注释并对其进行修改.

Store the complete user object - at least what I need for the comment (picture, name and such) in each comment. This redundancy could become troublesome to manage, since each time a user changes something (relevant to the data stored in the comments) I would have to go through all the comments in the database and modify it.

在此处应用正确的模式是什么?

What is the correct pattern to apply here?

推荐答案

我刚刚解决了这个确切的问题.

I tackled this exact problem a while ago.

mongo中没有任何联接. 您必须手动处理联接.

There are no joins in mongo. You have to manually take care of the join.

您的选择是:

  1. 浏览每个评论条目,并为用户查询mongo.这就是你在做什么.
  2. 从评论中获取所有用户ID,查询mongo中与这些ID相匹配的用户,然后注意使用户与评论相匹配.这只是您所做的,但经过了一些优化.
  3. 在用户的评论或用户评论中嵌入用户.不建议这样做,这可能不是评论/用户的正确位置.
  4. 考虑在显示评论时需要用户提供哪些数据集,并将此信息嵌入评论中

我最后选择了最后一个选项.
我们在每个评论中嵌入了用户ID,名字和姓氏. 此信息不太可能更改(创建后甚至不允许更改?).
如果可以更改,那么使用update-user方法来使用新信息来更新相关注释就不太困难了(我们也这样做了).
所以现在不需要加入.

I ended up going with the last option.
We embedded the user id, first and last name in each comment. This info is unlikely to change (possibly not even allowed to change after creation?).
If it can change then it is not too hard to tailor the update-user method to update the related comments with the new info (we did that too).
So now no join is needed.

这篇关于存储/获取从Mongo/RectiveMongo中的列表引用的值的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆