Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

reactjs - Storing data from MongoDB to state - best option

I'm a newcomer to the MERN stack and just putting a little blog site project together for some practice...

In my case, I'm retrieving all the blog posts to list briefly on the home screen each with a link to the full blog article. In this case the data is already retrieved and stored in React state.

Question is, when I go to the full blog article is it better to take the data from the already retrieved full list of blogs saved in state or should I get the individual blog entry from the database again with using ID.

I'm confident implementing either - I'm just considering the best practice, or benefits/dangers of doing either? Could data get out of sync?

I'm a newbie - be gentle! Thanks for all advice.

question from:https://stackoverflow.com/questions/66045224/storing-data-from-mongodb-to-state-best-option

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think when fetching all blogs for home page, you should only fetch the data which you will show for each blog rather than fetching the whole blog. Lets assume each of your blog has following fields:

{
  "title" : "Title of blog",
  "body" : "This is my blog, ...."
  "comments": [comment1, comment2, ...]
  "upvotes" : [],
  "downvotes" : [],
  "author" : ObjectId("ref to the author schema"),
  "time" : 10:30 PM
}

on home page, i'm assuming you only need to show the author, title, time and some lines of the body so you need to only fetch those instead of getting the whole blog. For that you can use .select() function of mongoose:

const blogs = await Blogs.find({}).select({ title: 1, time: 1, body: 1, author: 1 });

This way, you will only be getting the data you require. By implementing this, when a user clicks on a blog to view it, you can re-fetch the whole blog and get the latest result (in case the blog was updated or new comments/votes were added, the changes will be reflected). Hope this answers your question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...