Your task is to build a blog using MongoDB, Mongoose, Express, and React.
- Create a repo named blog-app on github.com not on git.generalassemb.ly
- Add your teammates as collaborators
- Create a development branch
Your app should include the following:
- CRUD on the backend (an api where you can create, read, update, and delete blog posts)
- CRUD on the frontend (a react frontend that has axios calls that can create, read, update, and delete blog posts)
Include the concept of a user:
- A post belongs to a user
- A user can have many posts
Here is an example schema.
const User = new Schema(
{
username: { type: String, required: true },
email: { type: String, required: true },
posts: [{ type: Schema.Types.ObjectId, ref: 'posts' }]
},
{ timestamps: true }
)const Post = new Schema(
{
title: { type: String, required: true },
imgURL: { type: String, required: true },
content: { type: String, required: true },
userId: { type: Schema.Types.ObjectId, ref: 'users' }
},
{ timestamps: true }
)In your seed file you will have to:
- Create users
- Create posts and associate them with users
- Create the association between users and posts
Try using the mongoose populate() method to return users with their associated posts:
Here is an example express route using populate.
app.get('/users', async (req, res) => {
try {
const users = await User.find()
.populate('posts')
res.json(users)
} catch (error) {
res.status(500).json({ error: error.message })
}
})Tips
