how to insert multiple data fields in one string in mongodb nodejs - node.js

i am doing an invoice project using node.js in which i have to store multiple products in a string and my code is
the schema file
var mongoose = require('mongoose');
var autoIncrement = require('mongoose-auto-increment');
var invoiceSchema = mongoose.Schema({
date: String,
documentNo:Number,
vendorName:String,
pno:Number,
productName:String,
description:String,
quantity:Number,
costPrice :Number,
mrp:Number,
invoiceNo:Number,
advance:Number,
due:Number,
discount:Number,
Tax : String,
netTotal:Number,
size:String,
colour:String,
grandTotal:Number
},{collection:'invoice-data'});
var invoice = module.exports = mongoose.model('invoice',invoiceSchema);
now for routing
var product = require('../models/product');
var invoice= require('../models/invoice.js');
exports.addaInvoice=function(req, res) {
var date=req.body.date;
var invoiceNo=req.body.invoiceNo;
var vendorName = req.body.vname;
var pno = req.body.orderNo;
var productName = getElementById(req.body.productname);
var description = req.body.desc;
var colour = req.body.colour;
var size = req.body.size;
var quantity = req.body.quantity;
var costPrice = req.body.costPrice;
var mrp = req.body.mrp;
var amount=req.body.amount;
var discount=req.body.discount;
var discountvalue=req.body.discountvalue;
var netamount=req.body.netamount;
var advance = req.body.advance;
var due = req.body.due;
var Tax = req.body.Tax;
var netTotal = req.body.netTotal;
var subTotal = req.body.subTotal;
var grandTotal = req.body.grandTotal;
var newInvoice = new invoice({
date: date,
invoiceNo:invoiceNo,
vendorName:vendorName,
pno:pno,
productName:productName,
description:description,
colour:colour,
size:size,
quantity:quantity,
costPrice :costPrice,
amount:amount,
discount:discount,
discountvalue:discountvalue,
netamount:netamount,
mrp:mrp,
advance:advance,
due:due,
Tax :Tax,
netTotal:netTotal,
subTotal : subTotal,
grandTotal : grandTotal
});
newInvoice.save();
req.flash('success_msg',' purchase invoice added ')
res.redirect('/users/invoicedetails');
}
html code
<head>
<script type="text/javascript">
function calculate()
{
var quantity = document.getElementById('quantity');
var costprice = document.getElementById('costprice');
//var amount = document.getElementById('amount');
var result=quantity.VA*costprice.value;
//amount.value = result;
$("#amount").val(result);
}</script>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
</SCRIPT>
</head>
<div class="form-group">
<label class="col-md-4 control-label" for="date">date</label>
<div class="col-md-8">
<input id="date" name="date" placeholder="date" class="form-control input-md" type="date">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="invoiceNo">invoiceNo</label>
<div class="col-md-8">
<input id="invoiceNo" name="invoiceNo" placeholder="invoiceNo" class="form-control input-md" type="text">
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="vendorname">Vendor name</label>
<div class="col-md-8">
<select id="vendorName" name="vendorName" class="form-control">
{{# each items }}
<option> {{ this.vendorName}}</option>
{{/each}}
</select>
</div>
</div>
</td>
</tr>
</table>
<INPUT type="button" value="Add Product " onclick="addRow('dataTable')" />
<table class="table table-hover" >
<thead>
<tr>
<td>productno</td>
<td>productName</td>
<td>size</td>
<td>colour</td>
<td>quantity</td>
<td>costprice</td>
<td>MRP</td>
<td>amount</td>
<td>discount%</td>
<td>discount value</td>
<td>net amount</td>
</tr>
</thead>
<TABLE id="dataTable" class="table table-hover" >
<TR>
<td>
<input id="orderNo" name="orderNo" placeholder="productno" class="form-control input-md" required="" type="text">
</td>
{{# each items }}
<option value="{{ this.productid}}"> {{ this.productname}}</option>
{{/each}}
</select>
</td>
<td>
<select id="size" name="size" class="form-control-md">
{{# each items }}
<option > {{ this.size}}</option>
{{/each}}
</select>
<!-- Text input-->
</td>
<td>
<select id="colour" name="colour" class="form-control-md">
{{# each items }}
<option > {{ this.colour}}</option>
{{/each}}
</select>
</td>
<td>
<input id="quantity" name="quantity" placeholder="Quantity" class="form-control " type="text">
</td>
<td>
<input id="costPrice" name="costPrice" placeholder="costPrice" class="form-control" type="text" onChange="calculate()">
</td>
<!-- Text input-->
<td>
<input id="mrp" name="mrp" placeholder="mrp" class="form-control" type="text">
</td>
<td>
<td>
<input id="amount" name="amount" placeholder="amount" class="form-control" >
</td>
<td>
<input id="discount" name="discount" placeholder="discount%" class="form-control"type="text">
</td>
<td>
<input id="discountvalue" name="discountvalue" placeholder="discountvalue" class="form-control"type="text">
</td>
<td>
<input id="netamount" name="netamount" placeholder="netamount" class="form-control"type="text">
</td>
</tr>
</tbody>
</table>
<table>
<!-- Text input-->
<td>
<label class="col-md-8 control-label" for="advance">Advance</label>
<div class="col-md-4">
<input id="advance" name="advance" placeholder="Advance" class="form-control input-md" type="text">
</div>
<div class="form-group">
<label class="col-md-8 control-label" for="Tax">Tax</label>
<div class="col-md-4">
<select id="Tax" name="Tax" class="form-control">
<option value="14.50">14.10</option>
<option value="12.50">12.50</option>
</select>
</div>
</div>
</td>
</table>
</table>
<label class="col-md-8 control-label" for="netTotal">netTotal</label>
<div class="col-md-4">
<input id="netTotal" name="netTotal" placeholder="netTotal" class="form-control input-md" type="text">
</div>
<label class="col-md-8 control-label" for="subTotal">SubTotal</label>
<div class="col-md-4">
<input id="subTotal" name="subTotal" placeholder="subTotal" class="form-control input-md" type="text">
<label class="col-md-8 control-label" for="grandTotal">grandTotal</label>
<div class="col-md-4">
<input id="grandTotal" name="grandTotal" placeholder="grandTotal" class="form-control input-md" type="text">
<label class="col-md-8 control-label" for="due">due</label>
<div class="col-md-4" align="left">
<input id="due" name="due" placeholder="due" class="form-control input-md" type="text">
</div>
<!-- Button -->
<div class="form-group" align="bottom">
<label class="col-md-4 control-label" for="vadd"></label>
<div class="col-md-4">
<button id="iadd" name="iadd" class="btn btn-primary">ADD</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
this is my html code in it the script is for cloning of the table for addingg a row in the tablle for multiple product entry
now this will work for one product if i have 2 or more products
how can i save these three products in a same document as like purchase invoice

If you are using bodyParser middleware, then you can pass an array of values from the client-side.
On client-side you might need to name your input elements as follows
<input name="products[#{1}][productname]" type="text">
<input name="products[#{1}][description]" type="text">
<input name="products[#{2}][productname]" type="text">
<input name="products[#{2}][description]" type="text">
and so on
This way your request body will have
{
"products": {
"1": {
"product name": "name goes here ",
"description": "desc goes here "
},
"2": {
"product name": "name goes here",
"description": "desc goes here"
}
}
}
You can iterate through that and get the values in your router as
var products = Array.prototype.slice.call(request.body.products);
for (var i = 0; i < messages.length; i++) {
var newInvoice = new invoice({
productName: products[i].productname,
description: products[i].description
});
newInvoice.save();
});

First you need to change your invoice schema to add multiple products in it. You need to add a array of product sub documents, I have added a sample schema below
// Product Schema
var ProductSchema = mongoose.Schema({
pno:Number,
productName:String,
description:String,
quantity:Number,
costPrice :Number,
mrp:Number,
size:String,
colour:String,
});
var invoiceSchema = mongoose.Schema({
date: String,
documentNo:Number,
vendorName:String,
products: [ProductSchema],
invoiceNo:Number,
advance:Number,
due:Number,
discount:Number,
Tax : String,
netTotal:Number,
grandTotal:Number
},{collection:'invoice-data'});
I haven't checked this code syntactically, I am just giving you an idea how to create schema if you want to store multiple sub documents in a single document.
And in your node.js code also, you need to save an array of products
var productArr = [];
var temProduct = {};
temProduct.pno= pno;
temProduct.productName= productName;
temProduct.description= description;
temProduct.colour= colour;
temProduct.size= size;
temProduct.quantity= quantity;
temProduct.costPrice = costPrice;
temProduct.amount = amount;
temProduct. = mrp;
productArr.push(temProduct);
var newInvoice = new invoice({
date: date,
invoiceNo:invoiceNo,
vendorName:vendorName,
products:productArr,
advance:advance,
due:due,
Tax :Tax,
netTotal:netTotal,
subTotal : subTotal,
grandTotal : grandTotal
});
newInvoice.save(function(err, new_data) {
if(err) {
// Handle error here, if any come
} else {
req.flash('success_msg',' purchase invoice added ')
res.redirect('/users/invoicedetails');
}
});
You can push as mush as products you want in productArr, then add it in invoice object and then save it.
I am mentioning again, that above code is not good to run directly, you need to do few changes, but it will give you an idea how to do it.

Related

How to retrieve older form data before updating it to new one using NodeJS, Express and mongodb! Ejs is the template?

I need to retrieve all older data of a form, before updating it to new one. I need those form data for a reporting purpose. It basically will be the version of a data.
I am working on #Nodejs #ExpressJS #EJS as template and #MONGODB,#mongoose.
Below are the images of the code! I am new to the programming so please help me with the coding part not describe it using coding Jargans!
Schema Snippet
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our user model
var procedureschema = mongoose.Schema({
proceduretype : String,
procedurename : String,
procedurenumber : String,
scope : String,
status:{type:String,lowercase:true,enum:["draft", "active", "pending"]},
forms : String,
relatedprocedure : String,
norms : String,
qualityrecords : String,
expdate : String,
companyname : String,
version : String,
owner: String,
approver : String,
procedurefiles : String,
flowchart : String,
proceduredescription : String,
isotags : String,
departmentname : String
});
// generating a password hash
// create the model for users and expose it to our app
module.exports = mongoose.model('Procedure', procedureschema);
Form view EJS page
<% include sidebar.ejs %>
<div class="dt-content">
<!-- Page Header -->
<!-- <div class="dt-page__header">
<h1 class="dt-page__title">New Procedure</h1>
</div> -->
<!-- /page header -->
<!-- Grid -->
<div class="row">
<!-- Grid Item -->
<div class="col-xl-12">
<!-- Card -->
<div class="dt-card">
<div class="dt-card__header">
<!-- Card Heading -->
<div class="dt-card__heading">
<h3 class="dt-card__title">New Procedure</h3>
</div>
<!-- /card heading -->
<a type="button" href="/admin/add/procedure/forms" role="button" class="btn btn-dark mr-2 mb-2"> Add Forms</a>
<a type="button" href="/admin/add/procedure/type" role="button" class="btn btn-dark mr-2 mb-2"> Add Procedure Type</a>
<a type="button" href="/admin/add/procedure/norms" role="button" class="btn btn-dark mr-2 mb-2"> Add Norms</a>
<a type="button" href="/admin/add/procedure/tags" role="button" class="btn btn-dark mr-2 mb-2"> Add Procedure Tags</a>
</div>
<!-- Card Header -->
<!-- /card header -->
<div class="dt-card__body">
<form action="/admin/create/procedure" method="post" enctype="multipart/form-data">
<div class="form-row">
<div class="col-sm-6 mb-3">
<label>Procedure Type</label>
<div class="input-group">
<select class="custom-select" name="proceduretype" id="inputGroupSelect04">
<option selected>Choose Procedure Type</option>
<% procedurecat.forEach(function(data){%>
<option value="<%=data.category_name %>"><%=data.category_name %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Procedure Name</label>
<input type="text" class="form-control" id="validationDefault03" name="procedurename" placeholder="Enter Procedure Name"
required>
</div>
<div class="col-sm-6 mb-3">
<label>Procedure Number</label>
<input type="number" class="form-control" name="procedurenumber" id="validationDefault03" placeholder="Enter Procedure Number"
required>
</div>
<div class="col-sm-6 mb-3">
<label>Scope</label>
<input type="text" class="form-control" id="validationDefault03" name="scope" placeholder="Enater Procedure Scope"
required>
</div>
<div class="col-sm-6 mb-3">
<label>Status</label>
<div class="input-group">
<select class="custom-select" name="status" id="inputGroupSelect04">
<option selected>Choose Status</option>
<option value="draft">Draft</option>
<option value="pending">Pending</option>
<option value="active">Active</option>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Forms</label>
<div class="input-group">
<select class="custom-select" name="forms" id="inputGroupSelect04">
<option selected>Choose Forms</option>
<% forms.forEach(function(data){%>
<option value="<%=data.forms_name %>"><%=data.forms_name %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Related Procedure</label>
<div class="input-group">
<select class="custom-select" name="relatedprocedure" id="inputGroupSelect04">
<option selected>Choose Related Procedures</option>
<% proceduretitle.forEach(function(data){%>
<option value="<%=data.procedurename %>"><%=data.procedurename %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Select Norms</label>
<div class="input-group">
<select class="custom-select" name="norms" id="inputGroupSelect04">
<option selected>Choose Norms</option>
<% norms.forEach(function(data){%>
<option value="<%=data.norms_name %>"><%=data.norms_name %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Quality Records</label>
<input type="text" name="qualityrecords" class="form-control" id="validationDefault03"
placeholder="Enter Quality Records Here" required>
</div>
<div class="col-sm-6 mb-3">
<label>Expiration Date</label>
<div class="input-group date" id="date-time-picker-1" data-target-input="nearest">
<input type="text" name = "expdate" class="form-control datetimepicker-input" data-target="#date-time-picker-1" />
<div class="input-group-append" data-target="#date-time-picker-1" data-toggle="datetimepicker">
<div class="input-group-text"><i class="icon icon-calendar"></i></div>
</div>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Company Name</label>
<input type="text" value="<%= user.companyname %>" name="companyname" class="form-control" id="validationDefault03" readonly
>
</div>
<div class="col-sm-6 mb-3">
<label>Version</label>
<input type="number" step ="0.1" name="version" class="form-control" id="validationDefault03" placeholder="Auto Increased field"
required>
</div>
<div class="col-sm-6 mb-3">
<label>Owner</label>
<div class="input-group">
<select class="custom-select" name="owner" id="inputGroupSelect04">
<option selected>Choose Owner</option>
<% users.forEach(function(data){%>
<option value="<%=data.name %>"><%=data.name %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Approver</label>
<div class="input-group">
<select class="custom-select" name="approver" id="inputGroupSelect04">
<option selected>Choose Approver</option>
<% users.forEach(function(data){%>
<option value="<%=data.name %>"><%=data.name %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-6 mb-3">
<label>Departmnent Name</label>
<div class="input-group">
<select class="custom-select" name="departmentname" id="inputGroupSelect04">
<option selected>Choose Department Name</option>
<% department.forEach(function(data){%>
<option value="<%=data.departmentname %>"><%=data.departmentname %></option>
<%})%>
</select>
</div>
</div>
<div class="col-sm-12 mb-3 form-row">
<label class=" col-form-label text-sm-left" for="file-field">Attached Files</label>
<div class="col-md-12 col-sm-9">
<div class="custom-file">
<input type="file" name="procedurefiles" onchange="GetFileSizeNameAndType()" id="file" class="custom-file-input" id="file-field" multiple>
<label class="custom-file-label" for="file-field">Attacthed your files here ..</label>
</div>
</div>
<div class="form-row input-group">
<div class="col-md-6 col-sm-6 form-row">
<div id="fp"></div>
</div>
</div>
</div>
<div class=" col-sm-12 mb-4 ">
<label class=" text-sm-left mb-4">Flowchart</label>
<button type="button" href="javascript:void(0)" role="button" class="btn btn-dark mr-2 mb-2">Design your flowchart</button>
</div>
<div class=" col-sm-12 mb-4 ">
<label>Description</label>
<textarea class=" col-sm-12 mb-4" name="proceduredescription" id="summernote"></textarea>
</div>
</div>
<hr class="border-dashed my-8">
<div class=" form-row mb-4 ">
<label class="col-md-2 col-sm-3 text-sm-right mb-4 mb-sm-0">Read Confirmation</label>
<div class="col-md-10 col-sm-9">
<!-- Checkbox -->
<div class="custom-control custom-checkbox custom-control-inline">
<input type="checkbox" id="customcheckboxInline1" name="customcheckboxInline1"
class="custom-control-input" checked>
<label class="custom-control-label" for="customcheckboxInline1"></label>
</div>
</div>
</div>
<hr class="border-dashed my-8">
<div class="form-group form-row mb-0 col-md-12">
<button type="submit" class="btn btn-primary text-uppercase">Submit this procedure</button>
</div>
</form>
</div>
<!-- Card Body -->
</div>
<!-- /card body -->
</div>
<!-- /card -->
</div>
<!-- /grid item -->
</div>
<!-- /grid -->
<!-- /site content -->
<% include footer.ejs %>
<script>
$(document).ready(function() {
$('#summernote').summernote();
});</script>
<script>
function GetFileSizeNameAndType()
{
var fi = document.getElementById('file'); // GET THE FILE INPUT AS VARIABLE.
var totalFileSize = 0;
// VALIDATE OR CHECK IF ANY FILE IS SELECTED.
if (fi.files.length > 0)
{
// RUN A LOOP TO CHECK EACH SELECTED FILE.
for (var i = 0; i <= fi.files.length - 1; i++)
{
//ACCESS THE SIZE PROPERTY OF THE ITEM OBJECT IN FILES COLLECTION. IN THIS WAY ALSO GET OTHER PROPERTIES LIKE FILENAME AND FILETYPE
var fsize = fi.files.item(i).size;
totalFileSize = totalFileSize + fsize;
document.getElementById('fp').innerHTML = document.getElementById('fp').innerHTML + '<br /> ' + 'File Name is <b>' + fi.files.item(i).name + "</b>.";
}
}
document.getElementById('divTotalSize').innerHTML = "Total File(s) Size is <b>" + Math.round(totalFileSize / 1024) + "</b> KB";
}
</script>
Routes of that form Post and Update API
app.post('/create/procedure', function (req, res) {
let proceduresinglefiles = req.files.procedurefiles
if(Array.isArray(proceduresinglefiles)==false){
console.log(Array.isArray(proceduresinglefiles));
console.log(typeof(proceduresinglefiles));
console.log(proceduresinglefiles);
var filename = proceduresinglefiles.name;
proceduresinglefiles.mv('./public/assets/documents/procedure/' + filename, function(err) {
if (err)
console.log(err);
});
var procedure = Procedure();
procedure.proceduretype = req.body.proceduretype;
procedure.procedurename = req.body.procedurename;
procedure.procedurenumber = req.body.procedurenumber;
procedure.scope = req.body.scope;
procedure.status = req.body.status;
procedure.forms = req.body.forms;
procedure.relatedprocedure = req.body.relatedprocedure;
procedure.norms = req.body.norms;
procedure.qualityrecords = req.body.qualityrecords;
procedure.expdate = req.body.expdate;
procedure.companyname = req.body.companyname;
procedure.version = req.body.version;
procedure.owner = req.body.owner;
procedure.approver = req.body.approver;
procedure.procedurefiles = filename;
procedure.flowchart = req.body.flowchart;
procedure.proceduredescription = req.body.proceduredescription;
procedure.isotags = req.body.isotags;
procedure.departmentname = req.body.departmentname
procedure.save(function (err, getprocedure) {
if (err) res.json(err);
else {
console.log(getprocedure);
res.redirect("/admin/view/procedure");
}
})
}
else
{
var filenamea=[];
for(var i=0;i<proceduresinglefiles.length;i++){
console.log(proceduresinglefiles.length);
console.log(i);
var procedurefilename = proceduresinglefiles[i].name;
console.log(procedurefilename);
filenamea[i]=procedurefilename;
console.log(filenamea);
proceduresinglefiles[i].mv('./public/assets/documents/procedure/' + procedurefilename, function(err) {
if (err)
console.log(err);
});
}
let multipleprocedurefilename= filenamea.toString();
var procedure = Procedure();
procedure.proceduretype = req.body.proceduretype;
procedure.procedurename = req.body.procedurename;
procedure.procedurenumber = req.body.procedurenumber;
procedure.scope = req.body.scope;
procedure.status = req.body.status;
procedure.forms = req.body.forms;
procedure.relatedprocedure = req.body.relatedprocedure;
procedure.norms = req.body.norms;
procedure.qualityrecords = req.body.qualityrecords;
procedure.expdate = req.body.expdate;
procedure.companyname = req.body.companyname;
procedure.version = req.body.version;
procedure.owner = req.body.owner;
procedure.approver = req.body.approver;
procedure.procedurefiles = multipleprocedurefilename;
procedure.flowchart = req.body.flowchart;
procedure.proceduredescription = req.body.proceduredescription;
procedure.isotags = req.body.isotags;
procedure.departmentname = req.body.departmentname
procedure.save(function (err, getprocedure) {
if (err) res.json(err);
else {
console.log(getprocedure);
res.redirect("/admin/view/procedure");
}
})
}
});
app.post('/edit/procedure/:id',(req, res) => {
Procedure.findOneAndUpdate({_id:req.params.id},{
$set:{
proceduretype : req.body.proceduretype,
procedurename : req.body.procedurename,
procedurenumber : req.body.procedurenumber,
scope : req.body.scope,
status : req.body.status,
forms : req.body.forms,
relatedprocedure : req.body.relatedprocedure,
norms : req.body.norms,
qualityrecords : req.body.qualityrecords,
expdate : req.body.expdate,
companyname : req.body.companyname,
version : req.body.version,
owner : req.body.owner,
approver : req.body.approver,
procedurefiles : req.body.procedurefiles,
flowchart : req.body.flowchart,
proceduredescription : req.body.proceduredescription,
isotags : req.body.isotags,
departmentname : req.body.departmentname
}},
{new: true, upsert:true},
function(err, procedurenew){
if(err){
console.log(err);
}
else
{
console.log(procedurenew);
res.redirect('/admin/view/procedure')
}
}
)
});
As far as I understand your problem, you need the old data before updating it to new one?
So you need to change(new:false) in your query API and your API code looks like:
app.post('/edit/procedure/:id',(req, res) => {
Procedure.findOneAndUpdate({_id:req.params.id},{
$set:{
proceduretype : req.body.proceduretype,
procedurename : req.body.procedurename,
procedurenumber : req.body.procedurenumber,
scope : req.body.scope,
status : req.body.status,
forms : req.body.forms,
relatedprocedure : req.body.relatedprocedure,
norms : req.body.norms,
qualityrecords : req.body.qualityrecords,
expdate : req.body.expdate,
companyname : req.body.companyname,
version : req.body.version,
owner : req.body.owner,
approver : req.body.approver,
procedurefiles : req.body.procedurefiles,
flowchart : req.body.flowchart,
proceduredescription : req.body.proceduredescription,
isotags : req.body.isotags,
departmentname : req.body.departmentname
}},
{new: false, upsert:true},
function(err, procedurenew){
if(err){
console.log(err);
}
else
{
console.log(procedurenew);
res.redirect('/admin/view/procedure')
}
}
)
});
[DO VOTE TO THIS ANSWER, IF ITS HELPFUL TO YOU]

getting same id result for all

I am trying to edit the record but I get the same result on clicking the edit button. Result of selected is not coming instead the first one is coming every time. I want to fetch the detail on clicking the edit button.
Getting result
If I click edit button of anyone it gets same value as above picture
router.js
router.get('/editCategory/:id', async (req,res,next) => {
const { id } = req.params;
const categories = await Category.findById({_id: id });
res.render('category', {
categories
});
res.json(data);
});
router.post('/editCategory/:id', async (req,res,next) => {
const { id } = req.params;
console.log(req.body);
const ctgy = await Category.findOne(id);
Object.assign(record, req.body);
await ctgy.save();
res.redirect('/category');
});
category.ejs
<tbody>
<% for(var i = 0; i <categories. length; i++) { %>
<tr>
<td><%= i+1 %></td>
<td><%= categories[i].category %></td>
<td><%= categories[i].status %></td>
<td>
<!-- Button trigger modal -->
<button type="button" class="btn bg-blue-w rounded edit" data-toggle="modal" data-target="#changecategoryModal">Edit</button>
<!-- Modal -->
<div class="modal fade" id="changecategoryModal" tabindex="-1" role="dialog" aria-labelledby="changecategoryModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="changecategoryModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="/edit/<%= categories[i]._id %>" method="post" enctype="multipart/form-data" id="categoryform">
<div class="form-group">
<label class="label-text">change Category</label>
<input type="text" class="form-control" placeholder="Category" name="category" value="<%= categories[i].category %>">
</div>
<div class="form-group">
<label class="label-text">Change image</label>
<input type="text" class="form-control" placeholder="Category" name="category" value="<%= categories[i].status %>">
<!-- <input type="file" name="myimage" value=""> -->
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<input type="submit" value="submit" class="btn bg-red rounded" form="categoryform">
</div>
</div>
</div>
</div>
</div>
Delete
</td>
</tr>
<% } %>
</tbody>
Error is in the below Line
const { id } = req.params;
when you are trying to destructor the req.params object , the value of id is not set. That is why query is returning the first row document every time.
Try to log the value of id and check.
in the second route
const ctgy = await Category.findOne(id);
the findOne accepts the object eg: Category.findOne({_id:id})

Angular - Taking input from the user and checking the value of it into firebase data

I want to take the input from the user and check the value of it whether it matches the value exists in firebase database or not.
I want to build a login component which provides the functionality of signUp user and signIn. I know it can be implemented by Auth but I want to use custom data. I was able to perform CRUD operations.enter image description here
This is login.component.ts where I want to implement the function
export class LoginComponent implements OnInit {
adminval: string;
passwordval : string;
newnew : string = 'employeeService.loginData.admin';
loginList : LoginID[];
constructor(private employeeService : EmployeeService, private router : Router) { }
ngOnInit() {
this.employeeService.getLoginData();
var x = this.employeeService.getLoginData();
x.snapshotChanges().subscribe(item =>{
this.loginList = [];
item.forEach(element => {
var y = element.payload.toJSON();
y["$key"] = element.key;
this.loginList.push(y as LoginID);
})
})
}
onEdit(emp : LoginID){
this.employeeService.loginData = Object.assign({}, emp);
}
onLogin(loginForm : NgForm){
if(this.adminval == this.employeeService.loginData.admin){
alert("OK");
}
else
alert("Not OK");
}
}
Here the login.component.html file code
<body style="background-color:#DD3247">
<div class="container" style="padding-top: 10%; padding-bottom: 8.1%;">
<div class="row justify-content-md-center">
<div class="col-md-5 login-box">
<h1 class="text-center login-text-color">Login</h1>
<hr>
<form #loginForm="ngForm">
<input type="hidden" name="$key" #$key="ngModel" [(ngModel)]="employeeService.loginData.$key">
<input type="hidden" name="admin" #admin="ngModel" [(ngModel)]="employeeService.loginData.admin" placeholder="Admin">
<input type="hidden" name="password" #password="ngModel" [(ngModel)]="employeeService.loginData.password" placeholder="Password">
<div class="form-row">
<div class="col-md-12">
<input type="text" class="form-control form-control-lg flat-input" name="adminvalue" #adminvalue="ngModel" [(ngModel)]="adminval" placeholder="Admin" required>
</div>
<div class="col-md-12">
<input type="password" class="form-control form-control-lg flat-input" name="passwordvalue" #passwordvalue="ngModel" [ngModel]="passwordval" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-login" (click)="onLogin(loginForm)">Login</button>
</div>
</form>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-md-center">
<h6 class="text-center">Employee Register</h6><br>
<table class="table table-sm table-hover">
<tr *ngFor="let login of loginList">
<td>{{login.admin}}</td>
<td>{{login.password}}</td>
<td>
<a class="btn" (click)="onEdit(login)">
<i class="fa fa-pencil-square-o"></i>
</a>
<a class="btn">
<i class="fa fa-trash-o"></i>
</a>
</td>
</tr>
</table>
</div>
</div>
</body>
Somehow, I was able to do it by matching username value but by the wrong implementation. You can see there are 3 input hidden fields in the HTML file so first I have to click on the edit icon then that will insert the existing data into the hidden fields and then if the input from the adminval matches the one of the admin hidden field then it will show OK otherwise Not Ok.

How to update a record using Sequelize?

I am trying to update the records form a table by using Sequelize.
Unfortunately, the id of the event I am trying to update seems to be undefined. How can I send it correctly?
The block of code I have in my controller looks like this:
router.get('/edit/:eventid', function(req, res) {
var eventid = req.params.eventid;
Event.findById(req.params.eventid).then(function(event) {
eventid= event.eventid;
title= event.title;
description= event.description;
availabletickets=event.availabletickets;
date= event.date;
newDate= date.toString();
newdate= newDate.substring(0,21);
console.log(eventid);
}) .then(function() {
res.render('eventEdit', {
eventid: eventid,
pagetitle: ' Edit Event',
title: title,
description:description,
availabletickets:availabletickets,
newdate: newdate,
});
})
.catch(function(error) {
res.render('error', {
error: error
});
});
});
router.post('/edit', function(req, res){
var eventid = req.body.eventid;
var title = req.body.title;
var description = req.body.description;
var availabletickets= req.body.availabletickets;
var date = req.body.date;
console.log( eventid); //this returns undefined.
console.log('title, description, availabletickets, date);
const newData = {
title: title,
date: date,
description: description,
availabletickets: availabletickets
};
Event.update(
newData,
{
where:{
eventid:eventid
}
}
).then(function() {
console.log("Event updated");
res.redirect('/events');
}).catch(e => console.error(e));
});
Although, the HTML file,where the user introduces the values when editing the events, looks like this:
<div class="container">
<h2><%= pagetitle %> </h2>
<form method="post" action="/events/edit">
<div class="container">
<div class="col-md-12 ">
<div class="row">
<div class="col-md-12 ">
<input class="form-control" type="text" name="title" id="title" value="<%= title %>" placeholder="Titlu Eveniment" required="true">
<p style="color:#8B0000;"><small>*This field is mandatory</small></p>
<textarea rows=7 class="form-control" type="text" name="description" id="description" placeholder="Descriere Eveniment"><%= description %></textarea> <br>
<input class="form-control" type="text" name="availabletickets" id="availabletickets" value="<%= availabletickets %>"> <br>
<label> Data:<%= newdate %> </label> <br/>
<label>Cahnge event date:</label>
<input class="form-control" type="date" name="date" id="date" style="width:190px;" ><br>
<button class="btn" id="addValue" style="background-color:#8B0000; color:white;">Save</button>
<button class="btn btn-warning">Cancel</button>
</div>
</div>
</div>
</div>
</form>
</div>
You get the eventid as undefined because req.body doesn't contain the eventid (it's not passed from the client side). To pass it from the client side you have to add an input having the name="eventid" attribute.
In the EJS template you need to render the eventid value as a hidden input (<input type="hidden" ...)
You can do that by added in your form this line:
<input type="hidden" value="<%= eventid %>" name="eventid" />
This is the updated form code:
<div class="container">
<h2><%= pagetitle %> </h2>
<form method="post" action="/events/edit">
<input type="hidden" value="<%= eventid %>" name="eventid" />
<div class="container">
<div class="col-md-12 ">
<div class="row">
<div class="col-md-12 ">
<input class="form-control" type="text" name="title" id="title" value="<%= title %>" placeholder="Titlu Eveniment" required="true">
<p style="color:#8B0000;"><small>*This field is mandatory</small></p>
<textarea rows=7 class="form-control" type="text" name="description" id="description" placeholder="Descriere Eveniment">
<%= description %>
</textarea>
<br>
<input class="form-control" type="text" name="availabletickets" id="availabletickets" value="<%= availabletickets %>">
<br>
<label> Data:
<%= newdate %>
</label>
<br/>
<label>Cahnge event date:</label>
<input class="form-control" type="date" name="date" id="date" style="width:190px;">
<br>
<button class="btn" id="addValue" style="background-color:#8B0000; color:white;">Save</button>
<button class="btn btn-warning">Cancel</button>
</div>
</div>
</div>
</div>
</form>
</div>

Parsing nested data from select form with Angularjs

I'm trying to parse a model from a form which contain a select(ngOptions) and save it to db but the selected value is never parsed. i'm stuck here can someone help please.
here is my code:
View
<section class="container" data-ng-controller="TagsController" >
<h2><i class="fa fa-pencil-square-o"></i>Add a new Tag</h2>
<form class="form-horizontal col-md-5" data-ng-submit="create()">
<div class="form-group ">
<div class="controls">
<input type="text" class="form-control input-lg" data-ng-model="label" id="label" placeholder="Label" required>
</div>
</div>
<div class="form-group" data-ng-controller="CategoriesController" data-ng-init="find()">
<select class="form-control input-lg" ng-model="category._id" ng-options="category._id as category.label for category in categories">
<option value="">Choose a Category</option>
</select>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn">
</div>
</div>
</form>
</section>
controller
angular.module('mean.tags').controller('TagsController', ['$scope', '$routeParams', '$location', 'Global', 'Tags', function ($scope, $routeParams, $location, Global, Tags) {
$scope.global = Global;
$scope.create = function() {
var tag = new Tags({
label: this.label,
category: this.category
});
tag.$save(function(response) {
$location.path("tags/");
});
this.label = "";
this.category = "";
};
...
I found the problem so i will answer my question. The problem was due to architecture restrictions, Angularjs don't allow to nest a ng-controller inside an other one...

Resources