When editing item from table, it pulls/saves the wrong information - node.js

So, I am working on a CRUD application and I am trying to make it so that I can edit the project when I click edit. I can successfully get the project ID with the req.params.id and it is successfully printing the correct information into the console but when I go to send it to my front end it is still updating the information for the first entry in the collection. Below is the code that I used for this.
Backend:
router.get('/edit/(:id)', function (req, res, next) {
var o_id = new ObjectId(req.params.id).toString();
db.collection('projects').find({
"_id": ObjectId(o_id).toString
}).toArray(function (err, result) {
if (err) return console.log(err)
// if user not found
if (!result) {
req.flash('error', 'Project not found with id = ' + req.params.id)
res.redirect('/projects')
} else { // if user found
console.log(result);
// render to views/user/edit.ejs template file
res.render('edit.ejs', {
user: req.user,
title: 'Edit User',
//data: rows[0],
projID: result[0]._id,
projName: result[0].projectName,
projStat: result[0].status,
projEngineer: result[0].engineer,
projCost: result[0].finalCost
});
}
});
});
Frontend for listing the projects:
<tbody>
<form action="/edit/<%=projID%>" method="post" class="d-flex align-self-center mx-auto" style="width:500px;height:500px;padding:0px;margin:0px;background-color:rgb(255,255,255);">
<tr>
<td>
<input type="text" class="form-control" name="projName" value="<%=projName %>">
</td>
<td>
<input type="text" class="form-control" name="projStat" value="<%=projStat %>">
</td>
<td>
<input type="text" class="form-control" name="projEngineer" value="<%=projEngineer %>">
</td>
<td>
<input type="text" class="form-control" name="projCost" value="<%=projCost %>">
</td>
</tr>
<button class="btn btn-primary btn-block" type="submit" style="background-color:rgb(4,148,74);">Submit</button>
</form>
</tbody>
Front end for editing
<tbody>
<form action="/edit/<%=projID%>" method="post" class="d-flex align-self-center mx-auto" style="width:500px;height:500px;padding:0px;margin:0px;background-color:rgb(255,255,255);">
<tr>
<td>
<input type="text" class="form-control" name="projName" value="<%=projName %>">
</td>
<td>
<input type="text" class="form-control" name="projStat" value="<%=projStat %>">
</td>
<td>
<input type="text" class="form-control" name="projEngineer" value="<%=projEngineer %>">
</td>
<td>
<input type="text" class="form-control" name="projCost" value="<%=projCost %>">
</td>
</tr>
<button class="btn btn-primary btn-block" type="submit" style="background-color:rgb(4,148,74);">Submit</button>
</form>
</tbody>

So I figured out my issue, the way I was querying the db returned all of the objects, I just had to loop over it and find where the id matches up. Thanks to #andreiNikolaenko for pointing out to check that.

Related

How to sent an id outside the loop of handlebars to the form inside the handlebars?

<form method="POST" action="/admin/update-blog/{{blogs._id}}">
<div class="form-group">
<label for="exampleInputPassword1">HEADING</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" value="{{blogs.heading}}" name="heading">
</div>
<br><br>
<div class="form-group">
<label for="exampleInputPassword1">BLOG</label>
<input type="text" class="form-control" id="exampleInputPassword1" value="{{blogs.blog}}" name="blog">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<br><br>
<h2><i><b>Comments</b></i></h2>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Email</th>
<th scope="col">Message</th>
</tr>
</thead>
<tbody>
{{#each blogs.comments}}
<tr>
<th scope="row"></th>
<td>
<form method="POST" action="/admin/delete-comment">
<div class="form-group">
<label for="exampleInputEmail1"></label>
<input type="email" class="form-control" id="myInput"readonly aria-describedby="emailHelp" placeholder="Enter email" value="{{this.email}}" name="email">
</div>
<button type="submit" class="btn btn-danger">delete</button>
</form>
</td>
<td>{{this.message}}</td>
</tr>
{{/each}}
</tbody>
</table>
How can i pass the {{blogs._id}} to a form which is inside a loop called {{#each blogs.comments}} .Is that possible.I am trying to delete a comment based on the email and the id of blog.Here the blog id is there in the top of code which is the first form where it displays the blog .And in the second form it displays the comments for the blog.
For me it is not possible to pass the id from blog to second loop(display comment).
I want to pass the id of blog to the action of the form in second loop(display comment)
THANKS IN ADVANCE😊
<option value="{{id}}">{{title}} {{../externalValue}}</option>
//The ../ path segment references the parent template scope that should be what you want.

how to submit form with multiple form field bearing the same name to database table in flask

I trying to submit items in a shopping cart to a database table but I can't get a clear understanding or how to implement it using the documentation on WTFORMS and other online materials I came across.
I have this forms in my forms.py:
class CartForm(Form):
amount = IntegerField('Price')
item_name = StringField('Product Name')
quantity = IntegerField('Quantity')
item_total_amount = IntegerField('Item Total')
class MainForm(FlaskForm):
total_amount = IntegerField('Total Amount')
cart_items = FieldList(
FormField(CartForm),
min_entries=1,
max_entries=20)
and this is the form in my template:
checkout.html
<form name="cart" action="{{ url_for('posts.checkout') }}" method="post"
enctype="multipart/form-data">
<table class="timetable_sub">
<thead>
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
{% for item in user_cart %}
</tr>
<tr name="line_items">
<td><input type="text" name="item_name " value="{{item.item_name }}"></td>
<td><input type="number" name="quantity " value="{{item.quantity}}"></td>
<td><input type="number" name="amount" value="{{item.amount}}"></td>
<td>
<input type="number" name="item_total_amount "value="item_total_amount
</td>
</tr>
{% endfor %}
</tbody></table>
<input type="number" name="total_amount" value="total_amount">
<input type="submit" value="Register">
</form>
I will appreciate a tutorial link or code base that can help me send this looped for fields to the database table

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 can I differentiate between two POST calls in expressjs?

I currently have two different forms on one inven.ejs file:
One for simple description:
///inven.ejs
<form method="POST" value="inven">
<div id="some-form" style="display: none;">
<table>
<tr>
<td><label for="item">Item</label></td>
<td><input type="text" name="item" required/></td>
</tr>
<tr>
<td><label for="text-box-value">Value</label></td>
</tr>
<tr>
<td><label for="comments">Comments</label></td>
<td><textarea rows="4" cols="50" required></textarea></td>
</tr>
<tr>
<td><input type="submit" /></td>
</tr>
</table>
</div>
</form>
and another for file upload:
///inven.ejs
<div id="fileUp">
<form id="fileUpload" name="fileUpload" enctype="multipart/form-data" method="post">
<fieldset>
<input type="file"id="fileSelect">
<input type="submit" name="upload" value="upload">
</fieldset>
</form>
</div>
In express, how can I differentiate between these two posts in my list.js file?
router.post('/list', function(req,res){
// ???
});
Do I need two routers? Am I completely doing this incorrectly?
Thank you!
EDIT:
Included an image, if it helps?
It makes sense to have forms post to a different address.
That is, <form id="fileUpload" action="file_upload" ... >
Then, if the form is found at http://server/my_form, it will post to http://server/file_upload
In your Node.js router you need to catch that and done.
If you still desire to send both forms to the same address, you can then use hidden fields.
Example: <input type="hidden" name="form_type" value="file_up_form">. Then in your Node.js you check for the argument form_type and check its value.

Resources