Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Connecting Database to Existing API (GET) | Section
Working with MongoDB in Express Applications

bookConnecting Database to Existing API (GET)

Swipe um das Menü anzuzeigen

So far, data may have been stored in arrays or temporary variables. Now you replace that logic with database queries.

Instead of returning hardcoded data, you use the model to fetch data from MongoDB.

app.get('/users', async (req, res) => {
  const users = await User.find();

  res.json(users);
});

For a single item:

app.get('/users/:id', async (req, res) => {
  const user = await User.findById(req.params.id);

  res.json(user);
});

Examples:

  • '/users': returns all users from database;
  • '/users/123': returns user with id 123 from database.

This replaces in-memory data with real database data.

question mark

What changes when connecting your API to a database?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 11

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 1. Kapitel 11
some-alt