זה נושא דיון מלווה לערך המקורי ב- https://www.tocode.co.il/bundles/nodejs/lessons/43-lab-mongoose-2
זה נושא דיון מלווה לערך המקורי ב- https://www.tocode.co.il/bundles/nodejs/lessons/43-lab-mongoose-2
Hi Ynon!
Regarding first exercise to list counted tags - I took posts of current page only,
as there is pagination there .
Then I added statics countTopics and query countTopics functions,
to Post model
and then used it in posts route to add to index.ejs to display each topic count.
It works.
Please take a look if I did it the right way.
Thank you
That’s my second exercise
Most of stuff is in routes and models.
I did my best to keep routes as thin as possible.
Good mongoose practice, remarks are welcome
תודה
Hi @avrahamm,
What do you think are the advantages of saving the “tags” in the same model? What were the advantages of keeping it in an external model?
I also noticed your function:
topicSchema.statics.getTopicsIds = async function(topicsStr)
In the second exercise does something weird. It uses a map with an async function and has “await” inside the map body.
This will cause the function to (potentially) run for a long time, as all “await” calls need to complete before you can return a result.
The best approach here is to use something I didn’t show in the course - and that’s mongodb aggregation framework. You can read about it here:
https://docs.mongodb.com/manual/aggregation/
And here’s an example to count tags arrays:
If this topic interests you do take the time to learn about the aggregation framework
it’s very powerful
Advantages of keeping in same model is that tags of each post are immediately available.
Advantages of keeping in separate Tag model is when needs to manage complementary data,
to avoid data duplication and ease in updating.
Thank you for your remark about putting await in each map callback iteration,
and for pointing to mongodb aggregation framework.
For now just rewrote the same code with better use of Promise.all
to avoid await map iteration - in getTopicsIdsV2 method in Topic model.
And noted for myself about mongodb aggregation framework for the future learning.
תודה