Home > Software engineering >  Api Post 400 Bad Request
Api Post 400 Bad Request

Time:08-11

I'm making a post API on a dummy node project; it worked fine there, but implemented the same API on the main project I got the 400 Bad request error while running this API on a post.

Route js

router.post("/add",(req, res) => {
  const planName = req.body.planName;
  const planPrice = req.body.planPrice;
  const planMode = req.body.planMode;
  const planStatus = req.body.planStatus;

  const newAddon = new Addon({
    planName,
    planPrice,
    planMode,
    planStatus,
  });
  console.log("newAddon", newAddon)

  newAddon.save()
    .then(() => res.json("Addon added"))
    .catch(err =>
      res.status(400).json("Error in Add Addon route")
    );
});

Schema

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const addonsSchema = new Schema(
    {
        planId: {type: Number,required: true},
        planName: {type: String,required: true},
        planPrice: {type: Number,required: true},
        planMode: {type: String, required:true},
        planStatus: {type: String, required:true}, //active or inactive
    },
    {timestamps: true},
);

const Addon = mongoose.model("Addons", addonsSchema);
module.exports = Addon

index.js

const addonRouter = require('./routes/addon')
app.use('/addons',addonRouter)

Postman Screenshot enter image description here

CodePudding user response:

You'll need to provide planId as well in the payload, since you've defined required as true.

You've 2 ways to solve this:

  1. Set the value of planId equal to _id field that mongodb creates automatically before inserting. You can do this with a preSave hook on the model.

     addonsSchema.pre("save", (next) => {
         // only triggered when creating new records
         if (this.isNew) {
             this.planId = this._id;
         }
         next();
     });
    

    And your type for planId should be ObjectId.

    planId: {type: ObjectId,required: true},
    
  2. Won't recommend but you can remove required attribute from planId.

  • Related