The POST Request will exclusively provide the ID in JSON format without including any other data

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.

Answer №1

Within your code snippet, you are setting the result of the save method:

router.post("/", async (req, res) => {
  let category = new Category({
    name: req.body.name,
    icon: req.body.icon,
    color: req.body.color,
  });
  // remove category = ...
  await category.save();

  if (!category) return res.status(400).send("the category cannot be created!");

  res.send(category);
});

If you eliminate this assignment, you should achieve the desired output.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript - The 'this' pointer becomes undefined while within a function body

I have set a value for this.username previously, but it returns as undefined when inside a function. How can I access its value? Parse.User.logIn(this.username, this.password, { success: function(user) { // it returns as undefined con ...

Can we stop Angular components from being destroyed during navigation?

Consider the scenario where I have two distinct Angular 2 components known as ComponentA and ComponentB. My goal is to navigate from ComponentA to ComponentB and then return to ComponentA without needing to reinitialize it. In the current setup of Angular ...

Issues with POST address when using Django and Ajax

Encountered a peculiar issue with Django and JQuery/Ajax involving URLs containing addresses: url(r'^app/insert$', Insert.as_view(), name="insert"), url(r'^app/insert_ajax$', Insert_Ajax.as_view(), name="insert_ajax"), url(r'^app/ ...

Determine whether a component is linked to an event listener

If a <Form> component is called with a @cancel event listener attached to it, the cancel button that triggers this event should be visible. If no @cancel event is present, the cancel button should not be displayed. Is there a method to verify if a c ...

I'm curious as to why the for-of loop within the function isn't producing the anticipated results that the regular for loop is achieving

Why is the behavior of the for...of loop different from the traditional for loop within this function? It appears that the 'el' in the for...of loop does not behave the same as iterable[i] in the regular for loop? var uniqueInOrder = function(it ...

Issue with XHR progress not functioning properly when cache is not cleared in CHROME

I will provide a detailed explanation of my issue. IMPORTANT-1: This issue arises with large files and under slow upload speed network conditions. IMPORTANT-2: The progress bar functions correctly in browsers like Edge. IMPORTANT-3: The problem only manif ...

What is the process for validating a json file using jsonschema?

Help needed with validating JSON input - my_json. An exception was expected due to discrepancy in keys. Any suggestions on how to validate this JSON data? import json from jsonschema import validate # Define the expected schema for the JSON. schema = { ...

A step-by-step guide on converting JSON data from JavaScript to C# variables

Hey there! I have a JavaScript snippet where I am sending an array to my C# file in JSON format. var r=['maths','computer','physics'] $.post("Global.aspx", { opt: "postpost", post: w.val(),tags:JSON.stringify(r) }, function ...

Comparing various indexes within an array using JavaScript array functions

I am currently facing a challenge with comparing non-consecutive indexes in an array. For instance, how can I compare index 0 with all the other indexes until reaching index 3 in a given array like this: const arr = ["Juan", "Maria", & ...

Why is the appsecret_proof invalid?

Currently, I am in the process of developing a new application. I am utilizing the Javascript API for logging in (v2.4) and the latest version of the PHP API (v5). To test the functionality of my app, I have created a Test App. With the Javascript API, I h ...

Ways to extract the source code of a webpage that has been modified on load

While working on extracting data from a website (completely within legal boundaries), I encountered an interesting situation. This particular site has 5 questions with answers on each page. However, upon inspecting the source code by pressing Ctrl+U, I no ...

What is the process for obtaining the hashed password to store in my database?

Despite being able to run a test in Postman, I am facing difficulties with passing my hashed password into the DB correctly. const express = require("express"); // const helmet = require("helmet"); const { User } = require("./db/mo ...

inputting an array of strings into the value attribute of an input element using jQuery

Whenever a user writes something in the input field with id="clientAdd" and presses enter, that text should be displayed as a tag inside a div. These tags are then saved as an array of strings, which I want to pass as the value for the hidden input field w ...

The useEffect hook is able to fetch data even when the state stored in the dependency array remains constant

I have been working on developing a quiz page that utilizes the useEffect hook to fetch data. The data retrieved includes the question as well as multiple-choice options. There is a button labeled Check Answer which, when clicked, reveals the user's f ...

Using the Jquery .each() method with Flickr JSON data

When looping over the JSON data returned from Flickr, I expected to alert 0, 1, 2, 3... for the index. However, it is actually alerting id, server, farm, etc. $.each(data.photo, function(index,item){ alert(index); }); UPDATE: By the way, I am utiliz ...

The script was denied execution due to the non-executable MIME type ('text/html') and the activation of strict MIME type checking

I'm currently attempting to retrieve data from the forismatic API, but I'm not receiving any response. I'm using AJAX in jQuery, however, I keep encountering the following error in my console: The script at '' was refused to execu ...

Troubleshooting AngularJS Directives' Cross-Origin Problems within Eclipse

Hello, I am facing an issue while using Angular JS in Eclipse. Specifically, when attempting to use Directives, I encounter a problem with the Cross-Origin Resource Sharing (CORS) policy when loading the Directives template in the index.html file. XMLHttp ...

Tips for swapping content between table rows in JavaScript

Struggling to rearrange a table with a new order due to performance issues. Here is a simplified version of the structure: <table> <tr id="row1"></tr> <tr id="row2"></tr> <tr id="row3"></tr> <tr id="row4">&l ...

Convert your dictionary into an object using JOLT!

I am looking to utilize JOLT Transform in order to convert a dictionary into a JSON Object. Below, I provide an example demonstrating this concept. At the root level, there is an Array containing results from different computers such as "Computer1", "Comp ...

Problems encountered with React Image Magnifiers while attempting to zoom in with Next.js

When I try to use the react-image-magnifiers plugin to make an image zoom in on hover, it works fine without next.js. However, when I integrate it with next.js, the zoom functionality does not work. Could there be an issue in my next.config.js file? This ...