Trying to make a POST request from Postman to Mongo Database. Currently, only the ID of the object is being returned and the data is not displaying.
Data Model:
const mongoose = require("mongoose");
const categorySchema = mongoose.Schema({
name: String,
icon: String,
color: String,
});
categorySchema.virtual("id").get(function () {
return this._id.toHexString();
});
categorySchema.set("toJSON", {
virtuals: true,
});
exports.Category = mongoose.model("Category", categorySchema);
Routes setup:
const { Category } = require("../models/category");
const express = require("express");
const router = express.Router();
// GET all categories
router.get(`/`, async (req, res) => {
const categoryList = await Category.find();
if (!categoryList) {
res.status(500).json({ success: false });
}
res.status(200).send(categoryList);
});
// GET a specific category by ID
router.get("/:id", async (req, res) => {
const category = await Category.findById(req.params.id);
if (!category) {
res
.status(500)
.json({ message: "The category with the given ID was not found." });
}
res.status(200).send(category);
});
// POST new category
router.post("/", async (req, res) => {
let category = new Category({
name: req.body.name,
icon: req.body.icon,
color: req.body.color,
});
category = await category.save();
if (!category) return res.status(400).send("the category cannot be created!");
res.send(category);
});
// PUT update category by ID
router.put("/:id", async (req, res) => {
const category = await Category.findByIdAndUpdate(
req.params.id,
{
name: req.body.name,
icon: req.body.icon || category.icon,
color: req.body.color,
},
{ new: true }
);
if (!category) return res.status(400).send("the category cannot be updated!");
res.send(category);
});
// DELETE category by ID
router.delete("/:id", (req, res) => {
Category.findByIdAndRemove(req.params.id)
.then((category) => {
if (category) {
return res
.status(200)
.json({ success: true, message: "the category has been deleted!" });
} else {
return res
.status(404)
.json({ success: false, message: "category not found!" });
}
})
.catch((err) => {
return res.status(500).json({ success: false, error: err });
});
});
module.exports = router;
POST Request URL: localhost:6426/api/v1/categories?name=Srihari&icon=%23srihari&color=srihari-icon
Base URL for Categories: localhost:6426/api/v1/categories
View the output in postman for POST request here
{
"_id": "62b58640a91799ea2bc2e1f7",
"__v": 0,
"id": "62b58640a91799ea2bc2e1f7"
}
The expected output should be a JSON object with all the Category parameters included.