Reputation: 567
This is the project, roughly: We have users and we have polls, users can both create polls or vote existing polls. Of course one user can vote just once each poll.
To me this is clearly relational, so in principle NoSQL makes no sense. But then I read a little and came to the conclusion that you can indeed make relations in MongoDB so I came to this scheme, I want to know if it is Mongo-ok or not before going on.
In a table/collection called users we store all the user data including an id (I guess default _id of mongo documents will be ok?)
In another table/collection called polls, we will have an id, the question, the possible answers and (here is where I start to have doubts) an array containing all the userIDs that had already voted? And then additionally the author's userID and also its username (I know this is duplicating but I read somewhere that I makes sense to do this in mongo, so that you don't have to launch another query just to know the user's username).
In MySQL I would have created a table with the voting relations (userID has voted pollID), but I guess in Mongo it makes sense to include this data in the poll document itself? Of course this array of userIDs will be constantly being updated, is that OK?
And what if I want to list all the polls created by a given userID? I know you can use find(), but is it as efficient as in MySQL at least for this case? Also each poll will be in a category and you would also must be able to sort by category and so, but I didn't wanted to complicate it further.
Upvotes: 0
Views: 48
Reputation: 5918
In my opinion, one efficient way to go about this would be to have a Users
collection in which you store all the data relating to your users, and then have a Polls
collection that, as you mentioned, stores an array of ObjectId
references back to your users.
This array can also contain some additional information such as a timestamp of when any given user has answered and the answer that was provided.
Still, be aware that it is not always a good practice to embed objects in an array, especially when it is unbounded (i.e.: the number of users will increase in time, thus making it possible for the references array on the Polls objects to also increase in time).
Nevertheless, I think that in your case this is a good approach to your application use case scenarios, especially since a user can only answer once to any given poll, thus limiting the rate of expansion of the array of objects.
Moreover, regarding your concern about querying the Polls collection by UserId, I think you will have no issue firing a find
query as long as you properly index your collection. If you are only interested in retrieving the total number of polls created by a certain user without retrieving data about those polls, an alternative might be having a counter
field defined on the user which would get incremented each time a user creates a poll.
Upvotes: 1