node.jsexpressmongoosemongoose-schema

How to create multiple API using Node.js, Express, and Mongoose


I am trying to create multiple express API in node.js using the modal schema. The issue i am facing if i create more than two API then third one (last one) is not working.

As you can see in the below screenshot. number 3.

showing all products.

showing single product.

not showing all categories.

1.showing entire collection. enter image description here

2.showing single row of collection based on ID. enter image description here

3.showing collection of specific column. enter image description here

here is module schema:

const mongoose = require('mongoose');

const ProductSchema = new mongoose.Schema({
    title: String,
    description: String,
    category: String,
})

const PostModel = mongoose.model("products", ProductSchema) //"table name", UserSchema
module.exports = PostModel

here is index.js

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');

//export module schema
const PostModel = require('./models/CreatePost')

// Middleware
const app = express()
app.use(cors());
app.use(express.json());

//define port
const port = 5000; 

//define database
mongoose.connect("mongodb+srv://username:<password>@cluster0.jvxew8i.mongodb.net/store")



//find by table ID
app.get('/products/:_id', function(req, res) {
  PostModel.findById(req.params._id)
  .then(products => res.json(products))
  .catch(err => res.json(err))
})


//find by table
app.get('/products', function(req, res) {
  PostModel.find()
  .then(products => res.json(products))
  .catch(err => res.json(err))
})


//find by specific column
app.get('/products/categories', function(req, res) {
  PostModel.find({}, {category: 1, _id: 0})
  .then(products => res.json(products))
  .catch(err => res.json(err))
})


// Server listen
app.listen(port, () => {
    console.log(`Server is running on port: ${port}`);
})

Solution

  • You are overlapping get these two routes '/products/categories' and '/products/:_id' .

    thus, the route with url params '/products/:_id' was specified before the main route '/products/categories' making it not accessible.

    you have to move this route :

    //find by specific column
    app.get('/products/categories', function(req, res) {
      PostModel.find({}, {category: 1, _id: 0})
      .then(products => res.json(products))
      .catch(err => res.json(err))
    })
    

    before this one :

    //find by table ID
    app.get('/products/:_id', function(req, res) {
      PostModel.findById(req.params._id)
      .then(products => res.json(products))
      .catch(err => res.json(err))
    })