REST API – GET Specific DB Record – Using Dynamic URL Value

Query and retrieve a specific Mongo DB record using Express JS REST API. Mongo DB findOne() method usage for retrieving single record from the database.

Using dynamic keyword receiving from the request URL. Get the data from the Mongo DB using Express JS code.

app.route('/articles/:articleTitle').get(function(req,res){

    Article.findOne(({title: req.params.articleTitle}), function(err, foundArticle) {
      if(err){
        console.log(err);
        res.send("No item found.")
      }else{
        res.send(foundArticle);
      }
  });
});

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);


//////////////////////////////////REQUEST TARGETING SPECIFIC ARTICLE////////////////////////////////////////////


app.route('/articles/:articleTitle').get(function(req,res){

    Article.findOne(({title: req.params.articleTitle}), function(err, foundArticle) {
      if(err){
        console.log(err);
        res.send("No item found.")
      }else{
        res.send(foundArticle);
      }
  });
});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

BONUS TIP

URL Encode Reference: https://www.w3schools.com/tags/ref_urlencode.ASP

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *