Retrieving Data from the MongoDB database using REST API – GET REQUST. Express JS code for the REST API – data retrieving code.
GET Request
app.get('/articles', function(req, res){ Article.find(function(err, foundArticles){ if(!err){ res.send(foundArticles); }else{ res.send(err); } }); });
Full Code
const express = require("express"); const bodyParser = require("body-parser"); const ejs = require("ejs"); const mongoose = require('mongoose'); const { response } = require("express"); const app = express(); app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static("public")); const uri = "mongodb://localhost:27017/wikiDB" mongoose.connect(uri, {useNewUrlParser: true, useUnifiedTopology: true}); const articleSchema = new mongoose.Schema({ title:String, content: String }); const Article = mongoose.model("Article", articleSchema); app.get('/articles', function(req, res){ Article.find(function(err, foundArticles){ if(!err){ res.send(foundArticles); }else{ res.send(err); } }); }); app.listen(3000, function() { console.log("Server started on port 3000"); });