**i m building an api for my website and the post method wont send data to mongodb it works from post man but sends empty feilds **
heres the code of express
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require('mongoose');
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(express.static("public/js"));
mongoose.connect("mongodb://localhost:27017/invoice_db", { useNewUrlParser: true });
const fromSchema = new mongoose.Schema({
title: String,
numebr: String,
email: String
})
const toSchema = new mongoose.Schema({
billing_name: String,
billing_address: String,
addInfo: String
})
const takeDate="1995"
const invoiceSchema = new mongoose.Schema({
invId: {
type: String
},
date: String,
issue_date: String,
from: [fromSchema],
to: [toSchema],
description: String,
Ptype: String,
quantity: String,
amount: String,
totalAmount: String,
gst: String
})
const Invoice = mongoose.model("invoice",invoiceSchema)
const From = mongoose.model("from",fromSchema)
const To = mongoose.model("to",toSchema)
// const invoice = new Invoice({
// invId:"abc12345",
// date:"12 12 12",
// issue_date:"10 10 10",
// from:[{
// title:"acb",
// numebr:"12345678",
// addInfo:"avi"
// }],
// to:[{
// billing_name:"wo",
// billing_address:"waha",
// billing_extra:"kuch ni"
// }],
// description:"akakka",
// Ptype:"v",
// quantity:"2",
// totalAmount:"25"
// })
// invoice.save()
app.get("/invoice-generateeee", (req, res) => {
res.render("invoice-generateeee")
})
app.post("/invoice-generateeee", function(req, res) {
// const from = new From({
// title: req.body.from_name,
// email: req.body.from_extra,
// numebr: req.body.from_address
// })
// from.save()
const inv = new Invoice({
invId: req.body.invId,
date: req.body.getDate,
issue_date: req.body.issue_Date,
from: [{
title: req.body.from_name,
email: req.body.from_extra,
numebr: req.body.from_address
}],
to: [{
billing_address: req.body.billing_address,
billing_name: req.body.billing_name,
addInfo: req.body.billing_extra
}],
description: req.body.item_name,
Ptype: req.body.item_type,
quantity: req.body.item_qty,
amount: req.body.item_rate,
totalAmount: req.body.totalA,
gst: req.body.item_gst
})
inv.save((err)=>{
if (err){console.log("lmao noob")}
else(console.log("done"))
})
})
app.listen(3000, function() {
console.log("Server started on port 3000");
});
here is the ejs front end
and here is the data base in which post nethod sends empty feilds
2
Answers
Try updating your code as mentioned below:
Note: You need some exposure on How to write Javascript
You need to add a body parser so that the body won’t be empty.
The easiest way you can do that is by adding the next line next to the other "app.use" statements.