bib
bib

Reputation: 1040

How to send data from a form to mongodb?

I am created a nodejs project the structure of py project is: enter image description here

api.js is:

const express = require('express');
const router = express.Router();

const add = require('../model/myModel');


router.get('/',function(req,res){
    res.render('myForm');
});


router.post('/add', (req, res) => {
    console.log(req.body)
    n = req.body.name,
    phone = req.body.phone,
    console.log(`name = ${n}`)
   
   let obj = new Address({
     name: n,
     phone: phone,
    });
   
   // add this instance to the database.
   obj.save()
   .then((address) => {

       res.send(address);
       })
    .catch((err) => {
        console.log(error);
        });
   });

module.exports = router;

and my app.js is:

const express = require('express');
const mongoose = require('mongoose');
const route = require('./route/api');
//Initialize express app
const app = express();

// Connecting to DB
const dbPath = 'mongodb://localhost:27017/testdb';
const dbOptions = {useNewUrlParser: true};


mongoose.connect(dbPath, dbOptions).then(()=>{
    console.log(`We are connected to our database ${dbPath}`);
}).catch((error)=>{
    console.log(`We are note able to connect to our database: ${error}`);
});

app.use(express.static('public'));
app.use(express.json());
app.set("view engine", "ejs");

// initialize routes
app.use("/api", route);

//Initialize the sever
app.listen(3000, () => {
    console.log('sever listening on port:3000');
});

and myForm.ejs is:

enter image description here

So, I want to be able to enter the data in myForm.ejs and save this data in the database. But when I fill the form and press submit my req.Body is an empty object. Where is my error?

Upvotes: 0

Views: 1507

Answers (2)

BG LAKSHMINARAYANA
BG LAKSHMINARAYANA

Reputation: 1

Use async await as it is a call from the database use this

router.post('/add', async (req, res) => {
console.log(req.body)
n = req.body.name,
phone = req.body.phone,
console.log(`name = ${n}`)

let obj = new Address({
 name: n,
 phone: phone,
});

await obj.save()
.then((address) => {
   res.send(address);
   })
.catch((err) => {
    console.log(error);
    });
});

Upvotes: 0

Someone Special
Someone Special

Reputation: 13588

Server side you need additional parser middleware

app.use(express.json());
app.use(express.urlencoded({ extended: true })); //add this line

Client side your form should use /api/add, and not /add

Upvotes: 1

Related Questions