DEV Community

Discussion on: Insert Data in MongoDB with Spring Boot - Building a Blog

Collapse
sdiamante13 profile image
Steven Diamante

Hey Rose! I have some constructive feedback on some of your code. It may look a bit cleaner if you use a constructor for your BlogPost model instead of using setters. Also you declared a MongoRepository interface, but never actually made use of it. From my own research it seems MongoTemplate is the better way to go since it's more flexible so I think you are on a good path. Keep up the great work! I'm making a YouTube series using the same stack: youtube.com/channel/UCxxHkYTfLe5EM...

Collapse
shadowphoenix profile image
Rose Author

Hey Steven!
Thank you for the feedback! I must admit that I had completely forgotten to write the constructor, so I'll definitely add that asap.
About the MongoRepository and MongoTemplate, it was hard to find proper resources and to figure out the actual difference between the two. I am using MongoTemplate and I think that somewhere in the process I figured that I had to use the MongoRepository in order to use MongoTemplate. I know, bit weird, but that's what you get when working with new stuff. ^,^" I definitely want to take a deeper dive into the difference between these two to figure out what's best for me to use.
I'll definitely check out your YT vid, and thanks again for the feedback! :D

Collapse
sdiamante13 profile image
Steven Diamante • Edited on

I can explain the difference between MongoTemplate and MongoRepository. So Mongo Repository is from Spring Data JPA. Out of the box you get methods like save, deleteById, findById, and findAllById. There's also a way you can write queries just by creating a specific method. So let's say you want to get a List if Blog Posts from a particular category you could define a method without any implementation called List findAllByCategory(String category). Under the hood Spring writes the appropriate query for you. It's pretty cool stuff!
MongoTemplate is a bit more lower level where you need to write your own queries. With embedded documents and denormalization it can be easier to write complex queries with MongoTemplate. For simple things I would use MongoRepository. I've seen some examples where both are used together in a hybrid approach. I hope that helps.