Connecting Database to Existing API (POST, UPDATE, DELETE)
Veeg om het menu te tonen
After connecting GET endpoints to the database, you update the rest of your API to use models instead of in-memory data.
For creating data:
app.post('/users', async (req, res) => {
const user = new User(req.body);
const savedUser = await user.save();
res.json(savedUser);
});
For updating data:
app.put('/users/:id', async (req, res) => {
const updatedUser = await User.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true }
);
res.json(updatedUser);
});
For deleting data:
app.delete('/users/:id', async (req, res) => {
await User.findByIdAndDelete(req.params.id);
res.send('user deleted');
});
Now all operations work with the database instead of temporary data.
This makes your API persistent and usable in real applications.
Was alles duidelijk?
Bedankt voor je feedback!
Sectie 1. Hoofdstuk 12
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Sectie 1. Hoofdstuk 12