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
const db = connection.db(dbName);
– Selects the database.const collection = db.collection("students");
– Selects thestudents
collection.collection.find().toArray()
– Gets all the data from the collection.resp.send(students);
– Sends the data as a response.
Test API with Thunder Client
- Open Thunder Client.
- Send a GET request to:
http://localhost:3200/api
You will see the data from the MongoDB students
collection.