Home > Mobile >  400 bad request when trying use the create in mongoose to save multiple records
400 bad request when trying use the create in mongoose to save multiple records

Time:09-21

I'm trying to save multiple records via mongoose and I was able to send the records once, however when I try to send the same records again I get a 400 bad request error message.

The records in the table:

empno    points    date_saved
 
72        15       "2021-09-20T17:21:30.366Z"
1000      0        "2021-09-20T17:21:30.366Z"
1001      10       "2021-09-20T17:21:30.366Z"

The model

const points_Schema = new mongoose.Schema({
  _id: {
    type: String,
    required: false,
  }, 
  empno: {
    type: Number,
    required: false,
  }, 
  points:{
    type: Number,
    required: false,
  },
  date_saved:{
    type: Date,
    required: false,
  } 
});

The Route

router.post("/points/save", (req, res) => {
 let newpoints = req.body;
  Points.create(newpoints, (err) => {
    if (err) {
      return res.status(400).json({
        error: err,
      });
    }
    return res.status(200).json({
      success: "points saved succesfully",
    });
  });
});

It works well when I request the first time when the collection is empty, but if I try to enter a another set of records I get the 400 error message. Any ideas how to solve this?

The Error with Postman

enter image description here

CodePudding user response:

remove this line maybe your problem related to primary key

_id: {
    type: String,
    required: false,
  },

CodePudding user response:

if you're using destructuring an object then you have to use

Try first console.log(newpoints) check that it's a int or still object.
let {newpoints} = req.body //this is correct way to destructuring an object

  • Related