Home > database >  post method not posting data in the data base express js / node js
post method not posting data in the data base express js / node js

Time:10-12

**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

enter image description here

and here is the data base in which post nethod sends empty feilds

enter image description here

CodePudding user response:

Try updating your code as mentioned below:

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
const path = require('path');

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

mongoose.connect("mongodb://localhost:27017/invoice_db", { useNewUrlParser: true });

const fromSchema = new mongoose.Schema({
    title: String,
    number: String,
    email: String
});
const From = mongoose.model("From",fromSchema);

const toSchema = new mongoose.Schema({
    billing_name: String,
    billing_address: String,
    addInfo: String
});
const To = mongoose.model("To",toSchema);

const invoiceSchema = new mongoose.Schema({
    invId: { type: String },
    date: String,
    issue_date: String,
    from: [{ type: mongoose.Schema.Types.ObjectId, ref: 'From' }],
    to: [{ type: mongoose.Schema.Types.ObjectId, ref: 'To' }],
    description: String,
    pType: String,
    quantity: String,
    amount: String,
    totalAmount: String,
    gst: String
});
const Invoice = mongoose.model("Invoice",invoiceSchema);

app.get("/invoice-generator", (req, res) => {
    Invoice.find()
        .populate('from')
        .populate('to')
        .exec((err, invoices) => {
            if (err) {
                throw err;
            }
            console.log(invoices);
            res.render("invoice-generator", {invoices: invoices});
        });
})

app.post("/invoice-generator", function(req, res) {
    const newFrom = new From({
        title: req.body.from_name,
        email: req.body.from_extra,
        number: req.body.from_address
    });

    newFrom.save((err, savedFrom) => {
        if (err) {
            throw err;
        }
        if (savedFrom) {
            const newTo = new To({
                billing_address: req.body.billing_address,
                billing_name: req.body.billing_name,
                addInfo: req.body.billing_extra
            });
            newTo.save((err, savedTo) => {
                if (err) {
                    throw err;
                }
                if (savedTo) {
                    const newInvoice = new Invoice({
                        invId: req.body.invId,
                        date: req.body.getDate,
                        issue_date: req.body.issue_Date,
                        from: [newFrom._id],
                        to: [newTo._id],
                        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
                    });
                    newInvoice.save((err, savedInvoice) => {
                        if (err) {
                            throw err;
                        }
                        console.log(savedInvoice);
                        res.send(savedInvoice);
                    })
                }
            });        
        }
    });
});

app.listen(3000, function() {
    console.log("Server started on port 3000");
});

Note: You need some exposure on How to write Javascript

CodePudding user response:

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.

app.use(express.json())
  • Related