REST API with Node.js & MongoDB

Make route for GET API

To get the data using the then method in Promise:

client.connect().then((connection) => {
app.get("/api", (req, resp) => {
const db = connection.db(dbName);
const collection = db.collection("students");

collection.find().toArray()
.then((students) => {
resp.send(students);
});
});
});


Fetch data from database

  1. const db = connection.db(dbName); – Selects the database.
  2. const collection = db.collection("students"); – Selects the students collection.
  3. collection.find().toArray() – Gets all the data from the collection.
  4. resp.send(students); – Sends the data as a response.


Test API with Thunder Client

  1. Open Thunder Client.
  2. Send a GET request to:
http://localhost:3200/api

You will see the data from the MongoDB students collection.