skip to Main Content

I’m facing an issue where I’m trying to store data from a form submission in MongoDB using Mongoose, but only the id field is being stored, while the other input fields are not saved. I have checked my schema definition and form setup, but I couldn’t identify the problem.

here is my code

const bodyParser = require("body-parser");
const express = require("express");
const path = require("path");
//const hbs=require("hbs");
const app = express();
const mongoose = require("mongoose");
require("./db/conn");
const Index = require("./models/index_schema");
const Doctor = require("./models/doctor_schema");
const Enterdetails = require("./models/enterdetails_schema");

const port = process.env.PORT || 80;

//const static_path =path.join(__dirname,"../public");
// Set the public directory as the static folder
app.use(express.static(path.join(__dirname, "public")));

app.use(express.urlencoded({ extended: false }));
app.use(express.urlencoded({ extended: true }));
// Middleware setup
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//app.use(express.static(static_path));
//app.set("view engine","hbs");
//app.use('views', express.static(path.join(__dirname,"views")));

// get request for index.html
//for index.html
// Serve index.html
app.get("/", (req, res) => {
  return res.sendFile(path.join(__dirname, "public", "index.html"));
});

/*app.get("/index",(req,res)=>{
    res.render("index");
})*/

//create a new user in database
app.post("/index", async (req, res) => {
  try {
    const indexSchema = new Index({
      name: req.body.name,
      phone_number: req.body.phone_number,
      password: req.body.password,
    });

    const userphn = await Index.findOne({ phone_number: req.body.mobile_number });

    if (!userphn) {
      return res.send("User not found"); // Send an error response if the user is not found
    }

    /*if (userphn.password !== req.body.password) {
        return res.send("Incorrect password"); // Send an error response if the password is incorrect
      }*/

    await indexSchema.save();
    console.log(indexSchema);
    res.status(201).redirect("index.html"); // Send a success response if everything is fine
  } catch (error) {
    res.status(400).send(error);
    console.log(error);
  }
});

// Serve enterdetails.html
// Serve enterdetails.html
app.get("/enterdetails.html", (req, res) => {
  return res.sendFile(path.join(__dirname, "public", "enterdetails.html"));
});

// Redirect to enterdetails.html
app.get("/open-enterdetails-page", (req, res) => {
  res.redirect("/enterdetails.html");
});

// const Enterdetails = mongoose.model('Enterdetails', enterdetailsSchema);

app.post("/enterdetails", async (req, res) => {
  try {
    const enterdetailsData = new Enterdetails({
      name: req.body.name,
      age: req.body.age,
      blood_group: req.body.blood_group,
      phone_number: req.body.phone_number,
      date: req.body.date,
      medical_history: req.body.medical_history,
      password: req.body.password,
    });
    console.log("Body: ", req.body);
    await enterdetailsData.save();
    console.log(enterdetailsData);
    res.status(201).send("/enterdetails.html");
  } catch (error) {
    res.status(400).send(error);
    console.log(error);
  }
});

// Serve doctor.html
app.get("/doctor.html", (req, res) => {
  return res.sendFile(path.join(__dirname, "public", "doctor.html"));
});

// Redirect to doctor.html
app.get("/open-doctor-page", (req, res) => {
  res.redirect("/doctor.html");
});

// post request for doctor.hbs
app.post("/doctor", async (req, res) => {
  try {
    const doctorSchema = new Doctor({
      name: req.body.name,
      phone_number: req.body.phone_number,
      password: req.body.password,
    });

    await doctorSchema.save();
    console.log(doctorSchema);
    res.status(201).redirect("/doctor.html");
  } catch (error) {
    res.status(400).send(error);
    console.log(error);
  }
});

app.listen(port, () => {
  console.log(`server is running at port no ${port}`);
});

all the values in my form would be stored in my MongoDB database successfully … but that isn’t the case … only the object id is stored.

2

Answers


  1. Chosen as BEST ANSWER

    after a lot of replacing the code ... i just replaced the same code with the original one and it worked

    her is my app.js code

    const bodyParser = require("body-parser");
    const express=require("express");
    const path = require("path");
    const app=express();
    const mongoose=require("mongoose");
    //const router=express.Router();
    require("./db/conn");
    const Index=require("./models/index_schema");
    const Doctor=require("./models/doctor_schema");
    const Enterdetails=require("./models/enterdetails_schema");
    
    
    //router
    //var fetchRouter = require('./models/fetch');
    //app.use('/', fetchRouter);
    //router.get('/fetch-data',fetchRouter.fetchData);
    
    
    
    
    const port =process.env.PORT  || 80;
    
    //const static_path =path.join(__dirname,"../public");
    // Set the public directory as the static folder
    app.use(express.static(path.join(__dirname, 'public')));
    
    
    
    app.use(express.urlencoded({ extended: false })); 
    app.use(express.urlencoded({ extended: true }));
    // Middleware setup
    app.use(express.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    
    
    
    // get request for index.html
    //for index.html
    // Serve index.html
    app.get('/', (req, res) => {
        return res.sendFile(path.join(__dirname, 'public', 'index.html'));
      });
      
    
    
    //create a new user in database
    app.post("/index", async (req, res) => {
        try {
          const indexSchema = new Index({
            name: req.body.name,
            date: req.body.date,
            phone_number: req.body.phone_number,
            password: req.body.password
          });
      
          const userphn = await Index.findOne({ phone_number: req.body.mobile_number });
      
          if (!userphn) {
            return res.send("User not found"); // Send an error response if the user is not found
          }
      
          /*if (userphn.password !== req.body.password) {
            return res.send("Incorrect password"); // Send an error response if the password is incorrect
          }*/
    
      
          await indexSchema.save();
          console.log(indexSchema)
          res.status(201).redirect("index.html"); // Send a success response if everything is fine
      
        } catch (error) {
          res.status(400).send(error);
          console.log(error);
        }
      });
    
    
    
        // Serve enterdetails.html
        // Serve enterdetails.html
    app.get('/enterdetails.html', (req, res) => {
      return res.sendFile(path.join(__dirname, 'public', 'enterdetails.html'));
    });
    
    // Redirect to enterdetails.html
    app.get('/open-enterdetails-page', (req, res) => {
      res.redirect('/enterdetails.html');
    });
      
      
      // const Enterdetails = mongoose.model('Enterdetails', enterdetailsSchema);
      
      app.post('/enterdetails', async (req, res) => {
        try {
          const appointment = new Enterdetails({
            name: req.body.name,
            age: req.body.age,
            blood_group: req.body.blood_group,
            phone_number: req.body.phone_number,
            medical_history: req.body.medical_history,
            password: req.body.password,
          });
      
          await appointment.save();
          console.log(appointment);
          res.status(201).send('/index.html');
        } catch (error) {
          res.status(400).send(error);
          console.log(error);
        }
      });
    
    
    
    // Serve doctor.html
    app.get('/doctor.html', (req, res) => {
        return res.sendFile(path.join(__dirname, 'public', 'doctor.html'));
      });
      
      // Redirect to doctor.html
      app.get('/open-doctor-page', (req, res) => {
        res.redirect('/doctor.html');
      });
    
    
    
    // post request for doctor.html
    app.post('/doctor', async (req, res) => {
      try {
        const doctorSchema = new Doctor({
          name: req.body.name,
          phone_number: req.body.phone_number,
          password: req.body.password,
        });
        const userphn = await Index.findOne({ phone_number: req.body.mobile_number });
      
          if (!userphn) {
            return res.send("User not found"); // Send an error response if the user is not found
          }
    
        await doctorSchema.save();
        console.log(doctorSchema);
        res.status(201).redirect('/doctor.html');
      } catch (error) {
        res.status(400).send(error);
        console.log(error);
      }
    });
    
    
    //post request for  table.html
    // app.get('/table.html', async (req, res) => {
    //   try {
    //     const userinfo = await Fetch.find();
    //     res.render('index', { fetchSchema });
    //     console.log(userinfo);
    //   } catch (error) {
    //     res.status(500).send(error);
    //   }
    // });
    
    
    //fetch all
    
    // app.get("/fetchdata",(res,req)=>{
    //   userTable.find((err,val)=>{
    //     if(err)
    //     {
    //       console.log(err);
    //     }else{
    //       res.render(val);
    //     }
    //   })
    // })
    
    
    
    app.listen(port, ()=>{
        console.log(`server is running at port no ${port}`);
    })
    

  2. If you are using Express version >= 4.16.0 then you don’t need bodyParser as it comes with Express.

    1. Check your package.json file and upgrade Express via npm if you need to.
    2. Delete app.use(express.urlencoded({ extended: false })); on line 18.
    3. Delete app.use(bodyParser.urlencoded({ extended: true })); on line 22.
    4. Delete app.use(bodyParser.json()); on line 23.

    This should get rid of the conflicting code you have here.

    Both express.json() and express.urlencoded() are needed for POST and PUT requests as your form is sending data to your Express server which then needs to store that data as an object. Now console.log(req.body) inside whichever post route you are submitting to and then submit your form. Check the console to see what’s in the body to see if the data from your form is there.

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