0

I am pretty new to node.js and building an billing web app. But in the Add Bill section, I can not able to insert the calculated total price to the database. I need to calculate the value of price after clicking submit button and then insert the value along with other values to the database. Even though my calculation is right, I am always getting value '0' in the DB under price.

Here is my code.

This is my bill schema

var bill = new Schema({
name:{type: String, required: [true, '{PATH} is required']},
cname: {type: String, required: [true, '{PATH} is required']},
address: {type: String, required: [true, '{PATH} is required'] },
city: {type: String, required: [true, '{PATH} is required'] },
postal: {type: Number, min: [0, 'Can not be a negetive value'], required: [true, '{PATH} is required']},
mobile: {type: Number, min: [0, 'Can not be a negetive value'], required: [true, '{PATH} is required']},
email: {type: String, required: [true, '{PATH} is required'] },
date: {type: Date, required: [true, '{PATH} is required'] },
product: {type: String, required: [true, '{PATH} is required'] },
//quantity: {type: Number, min: [0, 'Can not be a negetive value'] },
CGST: {type: Array},
SGST: {type: Array},
price: {type: Number}
});

This is in the route.js for send the request to controller.

router.post('/addbill', indexController.saveBill);

This in the controller.

saveBill: function(request, response) {
    var loginUser = request.session.user;
        var arr = [];
        var cgst = [];
        var sgst = [];
        var price = 0;
        arr = request.body.product;
        for(var i = 0; i<arr.length; i++){
            var query = Product.findOne({ pname: arr[i] });
            query.select('sell CGST SGST');
            query.exec(function (err, product){
                var tempPrice = product.sell;
                tempPrice = tempPrice + ((tempPrice * (product.CGST + product.SGST)) / 100);
                price = price + tempPrice;
                cgst[i] = product.CGST;
                sgst[i] = product.SGST;
                if (err) return handleError(err);
                console.log(price);// This printing the right results
            });
        }
        console.log("The Final Price: " + price);// 0
        console.log("The CGST: " + cgst);// Blank
        console.log("The SGST: " + sgst);// Blank
        var bill = new Bill({
            name: request.body.name,
            cname: request.body.cname,
            address: request.body.address,
            city: request.body.city,
            postal: request.body.postal,
            mobile: request.body.mobile,
            email: request.body.email,
            date: request.body.date,
            product: request.body.product,
            price: price,
            CGST: cgst,
            SGST: sgst
        });
        var error = bill.validateSync();
        if (error) {
            console.log(error);
            response.render('dashboard', {message: error, successMessage: '', userLoggedIn: loginUser});
        } else {
            bill.save(function (err) {
                console.log("Price from DB: " + bill.price);// 0
                if (err) {
                    // response.render('addemp', {message: 'OOPS something went wrong !!! Please try again', user: loginUser});
                    response.render('dashboard', {message: err, successMessage: '', userLoggedIn: loginUser});
                } else {
                    //response.redirect('/addemp');
                    response.render('dashboard', {successMessage: 'New Bill is successfully generated.', message: '', userLoggedIn: loginUser});
                }
            });
        }
}

Here is the json file from Database

{
"_id": {
    "$oid": "5ae591d36e2c9d1c39f159a9"
},
"CGST": [],
"SGST": [],
"name": "Ayan Das",
"cname": "Alliance Broadband",
"address": "15, Bidyayatan Sarani",
"city": "Kolkata",
"postal": 700035,
"mobile": 7003247631,
"email": "kenny.s@gmail.com",
"date": {
    "$date": "2018-04-29T00:00:00.000Z"
},
"product": "Redmi note 5 (black, 64Gb),Honor 9 Lite (Sapphire Blue, 32 GB)  (3 GB RAM),ACER ASPIRE V5-471p",
"price": 0,
"__v": 0

}

I think i'm missing something which i need to do in order to make it work. Mongoose documentation is kind of overwhelming for me, I did try some things from there but not working. Little help will be very helpful.

Ayan Das
  • 258
  • 1
  • 11
  • The "for loop" with `findOne()` statements. You cannot do that, see the first linked reference. There are other ways to "loop", but you probably want a "join". See the second reference. – Neil Lunn Apr 29 '18 at 09:45
  • For joining I can do that with mongoose populate but I need that outer loop as the request.body.product has multiple product names in an array. Can you elaborate me any other ways of "loop" for this condition. I think i need that "bill.save" inside the query callback with some kind of that loop intact cause even if manage to get the desired value to bill.price with populate, that bill.save executing before that resulting in price: 0 in DB. – Ayan Das Apr 29 '18 at 12:52
  • The "elaboration" is in the two linked answers already given. Look at the big box above your question, visit those answers, read and learn. Those cover your current mistakes – Neil Lunn Apr 29 '18 at 21:36

0 Answers0