MeteorJS + MongoDB: How do I set up my collections when users can have the same document?

I wasn't sure how to phrase my question in one line, but here's a more detailed description.

I am creating a Meteor application where users can "own" the same document. For example, a user has a list of movies they own, and of course, multiple people can own the same movie. There are several ways I have thought about structuring my database / collections to do this, but I'm not sure which would be better.

I should also note that the information about the movie comes from an external API that I currently store in my own database when people find it in my application to speed up the next search.

Option 1 (My current configuration): One collection (movies) that stores all movies and their information. Another collection that basically stores a list of movie IDs in each document based on userId. On startup, I get a list of IDs, find movies in my database and store them in local collections (there are 3 of them). The advantage I can see from this is that it only saves the movie once. The disadvantage I have encountered so far is the difficulty in synchronizing events and loading correctly at startup (waiting for local collections to fill).

Option 2: A movie collection that contains a list of movie objects for each user. This makes the initial search and update very easy, but it means I'll keep the same fairly large documents multiple times.

Option 3: A collection of movies with an array of users in every movie that belongs to that movie. This sounds good too, but when I update the movie with new information, will upsert work and keep users safe?

+3


source to share


1 answer


Option 3 seems reasonable. Some of the options may depend on the scale of each collection or the number of links (many users will have the same movie, whether users will have many movies).

Some useful code snippets for using option 3:

Speed ​​up movie detail (does not affect any other fields in the document if it already exists):

Movies.upsert({name: "Jaws"}, {$set: {year: 1975}});

      

Set that the user owns the movie (also does not affect any other fields of the document. $addToSet

Will not add the value twice if it is already in the array, but $push

will create duplicates instead ):

Movies.update({_id: ~~some movie id~~}, {$addToSet: {userIds: ~~some user id~~}});

      



Establish that the user no longer owns the movie:

Movies.update({_id: ~~some movie id~~}, {$pull: {userIds: ~~some user id~~}});

      

Find all movies the user owns (mongo looks for the field value automatically):

Movies.find({userIds: ~~some user id~~});

      

Find all the movies the user owns, but exclude the user field from the result (keep the document small if movie.userIds is a large array or protects the privacy of another owner of the custom movie):

Movies.find({userIds: ~~some user id~~}, {userIds: 0});

      

+1


source







All Articles