skip to Main Content

I am trying to take user input and then add a drug(medicine) to MongoDB. But it is not working and I am getting the error "Add proper parameter first". The user input should be patient name, drug name, dosage, frequency, adherence, and reason for not taking medicine. Please help!

app.post("/add-drug", (req, res) => {
  try {
    if (req.body && req.body.patient_name && req.body.drug_name && req.body.dosage && req.body.frequency && req.body.adherence && req.body.reason) {
      let new_drug = new drug();
      new_drug.patient_name = req.body.patient_name
      new_drug.drug_name = req.body.drug_name;
      new_drug.dosage = req.body.dosage;
      new_drug.frequency = req.body.frequency;
      new_drug.adherence = req.body.adherence;
      new_drug.reason = req.body.reason;
      new_drug.user_id = req.user.id;

      new_drug.save((err, data) => {
        if (err) {
          res.status(400).json({
            errorMessage: err,
            status: false
          });
        } else {
          res.status(200).json({
            status: true,
            title: 'Drug Added successfully.'
          });
        }
      });

    } else {
      res.status(400).json({
        errorMessage: 'Add proper parameter first!',
        status: false
      });
    }
  } catch (e) {
    res.status(400).json({
      errorMessage: 'Something went wrong!',
      status: false
    });
  }
});

The model file looks like this:


var mongoose = require('mongoose');
var Schema = mongoose.Schema;

drugSchema = new Schema( {
    patient_name: String,
    drug_name: String,
    dosage: Number,
    frequency: Number,
    adherence: Number,
    reason: String,
    user_id: Schema.ObjectId,
    
}),
drug = mongoose.model('drug', drugSchema);

module.exports = drug;

2

Answers


  1. The new_drug.save() method is asynchronous, so it returns a promise that you can await on:

    app.post("/add-drug", async(req, res) => {
       //...
       await new_drug.save();
    })
    
    Login or Signup to reply.
  2. it is supposed to be <field>:<value> inside your app.post method, not <field>=<value>

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search