How to write Mongo query to find data between dates - node.js

I want to get data of owner ID which lies between two dates using datePicker.
HTML
<form method="post">
<div class="col-lg-5 col-md-5">
<label>From</label>
<input type="date" class="form-control" ng-model="date.from" name="datefrom" />
</div>
<div class="col-lg-5 col-md-5">
<label>To</label>
<input type="date" class="form-control" ng-model="date.to" name="dateto" /> </div>
<div class="col-lg-2 col-md-2">
<button class="btn btn-primary " ng-click="getleaddate()">Go</button>
</div>
</form>
Node API
apiRoutes.post('/getleaddate', function(req, res){
var token=getToken(req.headers);
var owner=jwt.decode(token, config.secret);
Lead.find({ownerId:owner._id},date:{$gte :new Date(req.body.datefrom), $lte:new Date(req.body.dateto)},function(err, data){
if(err){res.json(err)}
else{
res.json(data);
console.log(data)
}
});
});
Above API is not working because req.body.datefrom and req.body.dateto is undefined
I don't know how to fix it.

please check the function for ng-click="getleaddate()"
Check the network tab on the request and request body sent .
it is working fine for me :
FormData:
datefrom:2017-01-11
dateto:2017-01-04
router.post('/test', function(req, res) {
console.log(req.body);
console.log(req.body.datefrom);
});
Console Output:
{ datefrom: '2017-01-11', dateto: '2017-01-04' }

Related

Update Operation in MongoDB with NodeJs

I am working on a Blog WebSite with CRUD operation I am able to achieve CRD operations but have issues with update One.
Issue:-
When I click on the edit button it opens the compose tab with the textfile loaded successfully but when I click on update it redirects to the home page but nothing Update, Please help me get out from this.
//This is the code for edit & Update Route
app.get("/posts/:postId/edit", (req, res) => {
Post.findById(req.params.postId, (err, post) => {
if (err) {
console.log(err);
} else {
res.render("edit", { post: post });
}
});
});
app.post("/posts/:postId/edit", (req, res) => {
Post.findByIdAndUpdate(
req.params.postId,
{
$set: {
title: req.body.title,
content: req.body.content,
},
},
(err, update) => {
if (err) {
console.log(err);
} else {
console.log("Post Updated");
res.redirect("/");
}
}
);
});
Form for the Edit/Update
//This is the Edit ejs file containing the update form
<form action="/posts/<%=post._id%>/edit/?_method=PUT" method="post">
<div class="mb-3">
<label for="post-title">Title</label>
<input class="form-control" id="post-title" name="postTitle" type="text" placeholder="Input title"
required autocomplete="off" value="<%=post.title%>">
</div>
<div class="mb-3">
<label for="postcontent">Post</label>
<textarea class="form-control text-area" id="postcontent" name="blog" rows="4" cols="50" required
placeholder="Start writing your blog ..............."><%=post.content%></textarea>
</div>
<button class="btn btn-primary publish-btn" type="submit" name="button">Update</button>
</form>
Your error is from the Ejs
You didn’t rename your req.body well to match your incoming data
You were meant to be used title instead of postTitle
And content instead of blog
Just edit your ejs to this and test gee
<form action="/posts/<%=post._id%>/edit/?_method=PUT" method="post">
<div class="mb-3">
<label for="post-title">Title</label>
<input class="form-control" id="post-title" name=“title" type="text" placeholder="Input title"
required autocomplete="off" value="<%=post.title%>">
</div>
<div class="mb-3">
<label for="postcontent">Post</label>
<textarea class="form-control text-area" id="postcontent" name="content" rows="4" cols="50" required
placeholder="Start writing your blog ..............."><%=post.content%></textarea>
</div>
<button class="btn btn-primary publish-btn" type="submit" name="button">Update</button>
</form>
If this answers your question mark it as done

Calling a PUT to express from EJS

I am trying to call a restful api created in expressjs from EJS form.
I tried looking on google and stackoverflow, and trying lots of different methods.
orders.ejs:
<ul class="orders">
<% for(var i=0; i<orders.length; i++) {%>
<ul class="order">
<p> coffee_id <span><%= orders[i].name %></span>
amount: <span><%= orders[i].amount %></span>
quantity <span><%= orders[i].quantity %></span> </p>
</ul>
<% } %>
</ul>
<div>
<form action="/orders" method="POST" action="orders/?_method=PUT">
<input type="text" placeholder="username" name="username">
<input type="text" placeholder="coffee name" name="name">
<input type="number" placeholder="amount" name="amount">
<input type="number" placeholder="quantity" name="quantity">
<button type="submit" id="order" >Submit</button>
</form>
</div>
nodejs.app.js:
app.post('/orders', (req, res) => { // falta o EJS
db.collection('orders').save(req.body, (err, result) => {
if (err) return console.log(err)
console.log(req.body);
res.render('orders.ejs', {
put: true
});
})
})
app.put('/orders/:coffeeid/:quantity', function(req, res) { ...
}
This code works fine individually calling them from Postman with the right parameters, but I need to call them both when I submit the EJS form.
app.get('/orders/:coffeeid',function(req, res) {
db.collection('orders').find({_id:req.params.coffeeid}).toArray, function(error,result){
if(!error && result && quantity){
return res.render('orders.ejs',{orders: result, coffeeid:result.coffeeid, quantity:'7'}); // <-- pass coffeeid to view
}
}
});
I need to read quantity also from the form and check for stock in the PUT, so for now I fixed it at '7'units, but now Cannot GET /orders
route for get orders :
app.get('/orders',function(req, res) {
// fetch all orders and display it to view
});
route for display edit page of order by coffeeid :
app.get('/orders/:coffeeid',function(req, res) {
var coffeeid= req.params.coffeeid;
db.collection('orders').find({_id:coffeeid}).toArray,function(error,result){
if(!error && result){
return res.render('orders.ejs',{orders:result,coffeeid:result.coffeeid, quantity:'7'});
}
});
});
form :
<form action="/orders/<%=coffeeid%>" method="POST">
<input name="_method" type="hidden" value="PUT">
<input type="text" placeholder="username" name="username">
<input type="text" placeholder="coffee name" name="name">
<input type="number" placeholder="amount" name="amount" value="">
<input type="number" placeholder="quantity" name="quantity" value="<%=quantity%>">
<button type="submit" id="order" >Submit</button>
</form>
to update information route will be :
app.put('/orders/:coffeeid', function(req, res) {
var coffeeid= req.params.coffeeid;
var quantity= req.body.quantity;
// save to database
}

using hbs engin and res.render shows page inside page

so I have this login page which ask users for 2 inputs, when user enter wrong values, it suppose to show error message (line of text), instead it showed the whole page inside the current page, and the message is shown in this page.
here is my hbs code:
<form action="/loginadmin" method="POST">
<div class="login100-form validate-form p-l-55 p-r-55 p-t-178" >
<span class="login100-form-title">
LogIn تسجيل الدخول
</span>
<div class="wrap-input100 validate-input m-b-16" data-validate="Please enter username">
<input type="text" name="Mobilenumber" id="Mobilenumber" placeholder="Mobile Number رقم الجوال">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Please enter password">
<input type="password" name="pass" id="pass" placeholder="Password الرقم السري">
<span class="focus-input100"></span>
</div>
</br>
<div class="container-login100-form-btn">
<button type="submit">
Login دخول
</button>
</div>
<p>{{ErrorMessage}}</p> <!-- this supposed to show error message -->
and here is the index.js part:
//to access the page:
router.get('/Loginpage', function(req, res, next){
res.render('/loginpage/index', {ErrorMessage: ''});
});
//form submission:
router.post('/loginadmin', function(req, res, next) {
//take from input:
var mobileValue = req.body.Mobilenumber;
var passwordValue = req.body.pass;
console.log(mobileValue);
console.log(passwordValue);
// database connection to mongo .. removed for simplicity
collection.find({mobile: mobileValue}).toArray(function(err, docs) {
if(!docs.length ){
console.log('mobile is not registered');
res.render("loginpage/index", {ErrorMessage: 'mobile is not registered'});//this part is causing the trouble I don't know why
}else{
//somethingelse//}
});
thanks,

Submitting a form results to a url segment undefined in NodeJs

I am setting up a simple form submission, when I submit the form the url becomes undefined
This is the view: http://localhost:3000/dashboard/tours/categories
router.get('/tours/categories', function (req, res) {
res.render('agents/tourcategories', {
page_link: 'wishlist'
});
});
This is the form:
<form method="POST" action="/dashboard/tours/categories" >
<div class="box_general padding_bottom">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Category Name</label>
<input type="text" name="categoryname" class="form-control" placeholder="e.g Hiking">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary pull-left" type="button" data-
dismiss="modal">Cancel</button>
<button id="" type="submit" class="btn btn-primary" >Save</a>
</div>
</form>
when I submit the form tne url changes to: `
http://localhost:3000/dashboard/tours/undefined
router.post('/tours/categories',function (req, res) {
console.log("We are here");
const category = new CategoriesDB({
categoryname: req.body.categoryname,
addedby: res.locals.useremail
});
// Save a Customer in the MongoDB
CategoriesDB.save(function (err) {
if(err){
console.log(err);
return;
}else{
res.redirect('/tours/categories');
}
})
});
I realy dont know where the undefined came from, I have checked everything seems to be okay. It keeps popping up in the url everythime i submit the form
`
From the snippets of the code you have posted, It might be because u have not used the middleware
router.all("/dashboard*");
But if u have used that and the GET request is working but not the POST then u will need to post more snippets of your code, mainly the middleware you defined to handle the routes

Uploading file to EC2 Web Server from Web Application

I am creating a simple application using Sails.js. What it basically does is it creates a new Item then saves it to the database and uploads the image to S3.
Here's what happens:
When I run my application on my local, it behaves okay. The req.body has contents, and the req.file('item-image') is not empty.
I am running it on EC2 now, and the problem is, the req.body is just an empty object, but the req.file('item-image') is not empty. I've tried different debugging scenarios, see them below:
If I remove the enctype="multipart/form-data" (I know this is needed for file upload, just trying), I get the req.body object that I expect, but as expected, the req.file('item-image') is empty.
I put back the enctype="multipart/form-data" then tried sending the request without the file, I get my expected req.body object.
I included an image on my request, the req.body object is empty, but the req.file('item-image') isn't.
The weirdest part is, when I send my request through postman, all behaves as expected. I'm really lost now, see my code below:
create_event.ejs
<form action=<%= event.createUrl %> method="POST" id="form-item" enctype="multipart/form-data">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="blue bigger">Please fill the following form fields</h4>
</div>
<div class="modal-body overflow-visible">
<div class="row">
<div class="col-xs-12 col-sm-5">
<div class="space"></div>
<input type="file" name="item-image"/>
</div>
<div class="col-xs-12 col-sm-7">
<div class="form-group">
<label for="form-field-username">Name</label>
<div>
<input class="input-large" type="text" id="form-field-username" placeholder="Item Name" name="item-name" />
</div>
</div>
<div class="space-4"></div>
<div class="form-group">
<label for="form-field-username">Description</label>
<div>
<input class="input-large" type="text" id="form-field-username" placeholder="Item Description" name="item-description"/>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-sm" data-dismiss="modal">
<i class="icon-remove"></i>
Cancel
</button>
<button class="btn btn-sm btn-primary" id="save-item">
<i class="icon-ok"></i>
Save
</button>
</div>
</div>
</div>
</form>
create_event.js
$('#save-item').on('click', function(e){
var response = confirm('Are you sure you want to continue saving this item?');
if(response == true) {
$('#form-item').submit();
}
});
AdminController.js
createItem: function(req, res){
console.log('Saving..');
console.log(req.body);
var eventId = req.path.split('/')[4];
req.file('item-image').upload(function callback(error, uploadedFile){
if(error) {
console.log(error);
return res.serverError();
}
console.log(uploadedFile);
s3Helper.upload(uploadedFile[0], function(error, data){
if(error) {
return res.serverError();
}
var item = {
ITEM_ID: uuid.v1(),
EVENT_ID: req.path.split('/')[4],
NAME: req.body['item-name'],
DESCRIPTION: req.body['item-description'],
IMAGE_URL: data.Location
}
EventItem.create(item, function(error, data){
if(error) {
console.log(error);
return res.serverError();
}
console.log('Successfully saved data: ');
console.log(data);
return res.redirect('/admin/events/' + eventId);
});
});
});
},
Thank you!
I found the answer here https://github.com/balderdashy/sails/issues/2508
Apparently, sails.js uses skipper and is sensitive on the order of the input. I just put the file part on the end and it now works.
I'm just confused as to why it works on my local, and not on my ec2 server.

Resources