Hi guys, I’m practicing my JS and now it comes that I need a database to make my pet project look more realistic. My project is a kind of blog where different users write articles, leave comments to articles and so on.
Base operations with MongoDB I’ve studied on my own, but now I’ve made a feature that a user can add articles to his favourites. I want to render a list of his favourite articles on his profile page.
There are separate collections for articles, and for users. Each User have a field “favouriteArticles”: […ids]. In the array id’s of articles he added to favourites.
How can I pass an array of articles id’s to Articles collection, find necessary articles and return an array of only names to render?
Ideally you want to include example documents (formatted with the buttons available in the editor) as well as sample output so that people can help you by putting the data straight into something like mongo playground.
In the mean time, it looks like you have already read the user record and have the favourite article array element and want to pass that to the Articles collection to filter.
You could do this with the $in operator:
If using a find operation, you can add a project to it to filter out the fields you want to return, or if using an aggregation use a $project to limit the fields returned.
Just to add something else to John’s suggestions: You could consider adding a compound index on both the id field that you are filtering on, and the name field that you want returned. If you include the projection as suggested by John to only return the name field, this would allow MongoDB to execute this as a “covered query” where it executes the search and builds the response entirely from the data in the index, without ever having to fetch and filter any documents from the corresponding collection. “Covered queries” can be very fast.
https://www.mongodb.com/docs/manual/core/query-optimization/#covered-query