Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Connecting Database to Existing API (POST, UPDATE, DELETE) | Section
/
Working with MongoDB in Express Applications

bookConnecting Database to Existing API (POST, UPDATE, DELETE)

Stryg for at vise menuen

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.

question mark

What is the main benefit of replacing in-memory data with a database?

Vælg det korrekte svar

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 12

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 1. Kapitel 12
some-alt