How to set sessions in Node JS

I am working with the session today in my current node js project. Actually i am creating a login page where i need to save user data in session and display him successfully logged in page.
First of all you need to install express node module "express-session". Below is the steps to set session in node js -

Step 1- First install session module by running below command


npm install express-session --save

Step 2- Initialization Session module on your server page like below


var express = require('express');
var session = require('express-session');
var app = express();
app.use(session({secret: 'phpsolution121',saveUninitialized: true,resave: true}));

Step 3- Now store your data into session like below 


sess=req.session;
var user_id = 25;
sess.user_id = user_id;

Step 4- Now it time to Access stored Session like below


sess=req.session;
sess.user_id

Don't forget to leave a comment below if you like this.

Chears 
Happy Coding :)

Error: "Unclean shutdown detected. Please visit http://dochub.mopngodb.org/core/repair for recovery instructions." in mongo db

When i run my mongo db from below command



C:\mongodb\bin\mongod 
Then i shown an error "Deleted data files in C:\data\db\ crated by the 'mmapv1' storage engine, so setting the active storage engine to 'mmapv1' Unclean shutdown detected. Please visit http://dochub.mopngodb.org/core/repair for recovery instructions." . See the below screen shot -


Error: "Unclean shutdown detected"

Solution : After googling some time finally i find out the solution of this problem which i want to share with all of my blog readers. 
I run the mongod command with --repair and then again i run mongod command and my mongo db is started successfully like below -

Step 1:  Run the mongod command with repair like below



C:\mongodb\bin\mongod\mongod --repair

Step 2: Now run again the mongod command like this



C:\mongodb\bin\mongod\mongod

Don't forget to leave a comment if you like this post.

Chears
Happy Coding :)

How to do pdf password protected in node js

Today i have a requirement in my node js project to do pdf password protect. So any one open that pdf he must be enter password then he can view the pdf content. I am doing a lots of googling but i didn't get the proper solution of it. There is no module of node which i can use to protect my pdf. So finally i write a command and i execute it in node js. Actually this is a very easy after writing few lines you can do it. Below is my code and method of uses.

This is my code :

var exec = require('child_process').exec;
var pdfsourcepath = '../client/app/loanpdf/loan_21213131.pdf'; // This is pdf path with pdf name with out encription.
var pdfdestinationpath = '../client/app/loanpdf/loan_encripted_21213131.pdf'; // This is encripted pdf path with pdf name.
var password = "test123";  //This is your password to decript pdf.
var command = 'qpdf --encrypt '+password+' '+password+' 40 -- '+pdfsourcepath+' '+pdfdestinationpath;

exec(command,
function (error){
 if (error !== null){
 console.log('exec error: ' + error);
 }else{
console.log('Your pdf is encripted successfully.');
 }
}
);


Dependency of this code : 

1- You have to install qpdf first on your server by run this command 

sudo apt-get install qpdf

2- Don't forget to inclule the "child_process" library on the top of your file. By default is it comes with the bundled of node.js. So you don't need to install it.

var exec = require('child_process').exec;

Output of this code like below screen shot -


Pdf password protected in node js

If you having any problem while using this code or you like this post don't forget to leave a comment below i will reply you back with your.

Chears
Happy coding :)

Error: [ngModel:numfmt] Expected `22323` to be a number http://errors.angularjs.org/1.5.0/ngModel/numfmt in angular js

Today i am facing a very strange problem in angular js. Actually i am working on a form there a many different types of input like text, number, radio , select etc.
I am also putting an input  type="number" to store only numeric values like below. 

Below is my html code :

<div class="control-group">
<label for="postcode" class="control-label">Post Code</label>
<div class="controls">
<input type="number" class="span4" placeholder="postcode" ng-model="company.postcode" ng-required="true">
<a class="req">*</a>
</div>
</div>


So far every thing is working fine but after saving record i am going to edit page to edit the same record of this input i shown an error i.e "Error: [ngModel:numfmt] Expected `22323` to be a number http://errors.angularjs.org/1.5.0/ngModel/numfmt?p0=22323" in the inspecter and nothing is shown in my input field like below :


Error: [ngModel:numfmt] Expected `22323` to be a number


Solution of this : Actually the problem is that when you get the data from database and trying to display in input type="number" field angular not able to parse it into integer. So its display error. So you have to parse(convert) it into integer and then send it to the input type="number" field to show it. 

Below is the simple directive to solve your problem:

.directive('stringToNumber', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$parsers.push(function(value) {
        return '' + value;
      });
      ngModel.$formatters.push(function(value) {
        return parseFloat(value, 10);
      });
    }
  };
});

Now when you are using input type="number" field then you have to call this directive to parse data of that input into integer like below:

<div class="control-group">
<label for="email" class="control-label">Post Code</label>
<div class="controls">
<input type="number" class="span4" placeholder="postcode" ng-model="company.postcode" ng-required="true" string-to-number>
<a class="req">*</a>
</div>
</div>

If you still having any problem or you like this post don't forget leave a comment.

Chear 
Happy Coding :)

How to send email with attachment using angular and node js or in mean stack

Today i am working on to send email using angular and node js. After googling alot finally i found a node module Node Mailer . Its a very nice module of node you can also send email via smtp by doing a very small configuration. In my below code i am not using smtp but if you need then can configuration setting according to the node mailer documentation.


Below is the steps to send email :


Step 1 : First of all you have to install the node mailer module. To do this just write  

npm install nodemailer

Step 2 : After that you have to include the node mailer libraries like below

var nodemailer = require("nodemailer");
var smtpTransport = nodemailer.createTransport();


Step 3 : Now this is my code to send email of my index.js node server file.

// This Is Use To Send Email.
app.post('/sendemail',function(req,res){
var attachment = (typeof req.body.attachment !="undefined") ? req.body.attachment : '';
var mailOptions = {
  from: "salman@phpsollution.blogspot.com",
  to: req.body.to,
  subject: req.body.subject,
  html: req.body.text,
     attachments:[{path: '/var/www/FAIRQUID/client/app/loanpdf/'+ attachment}]

}

smtpTransport.sendMail(mailOptions, function(error, info){
  if(error){
res.json({status: 'error'});
}else{
res.json({status: 'success'});
};
});
});


Step 4 : Now this is my http request code from angular js

var mailData = {
  to: 'naved.nice@gmail.com',
  subject: 'testing email',
  text: 'This is just a testing email send by the phpsollution.blogspot.com',
    attachment : pdfName
}

$http.post('/sendemail', mailData).success(function(data){
if(data.status == 'success'){
console.log("Email send successfully");
}
else{
console.log("Some error occour while sending email");
}
});


If you have any problem while using this code please comment below i will reply you back as soon as possible.

Chears 
Happy Coding :)

How to update a record in mongo db by "_id"

If you want to update a record in mongo db by "_id". Suppose below is a collection(table) with name "ceo" . So now you want to update name "Karm Khanna" with "Salman Ahmad"


Update a record in mongo db by "_id"


So now the update query will be like below :


db.ceo.update({"_id": ObjectId("56ab0b7fac34b55d1aa2b515") }, { $set: {"name": "salman ahmad"}});





Chears 
Happy coding :)

How to get first, second, third, fourth and last day date in javascript

I have created a function which is use to get date by the day and position in javascript. Actually my requirenment is when i passed day and its position then i got the date. To fullfil my requirenment i just created a function below.

For Example : Suppose if you want the second friday or last sunday or any thing else . You just need to pass the position and day then you get the corresponding date. 

function searchDayByPosition(searchday, searchposition){
var currentdate = new Date();
var currentmonth = currentdate.getMonth();
var currentyear = currentdate.getFullYear();
var lastDateOfMonth = new Date(currentyear, currentmonth+1, 0).getDate();
var searcharr = [];
for(var i=1;i<=lastDateOfMonth;i++) {
var day = new Date(currentyear, currentmonth, i).getDay();
if(day==searchday){
searcharr.push(i);
}
if(i==lastDateOfMonth){
if(searchposition!=5){
return searcharr[searchposition-1];
}else{
return searcharr[searcharr.length-1];
}
}
}

}


Description of function:
-----------------------------

1-- Sunday is 0, Monday is 1 .... and Saturday is 6 

2-- First denotes 1 , Second denotes 2 .... and Last denotes 5

3-- If you want the first sunday then you have to pass value like this searchDayByPosition(0, 1)

4-- If you want the last friday then you have to pass value like this searchDayByPosition(5, 5).

If you have any question related to this function comment below textbox i will reply you back.

Chears 
Happy coding :)



Error CORS header 'Access-Control-Allow-Origin' does not match 'example.com'

I am facing a serious problem in MEAN STACK. When i tried to get data from directly running url from browser then its return data but when i run the same url from ajax in Restangular its return error ie.  

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/companies. (Reason: CORS header 'Access-Control-Allow-Origin' does not match 'example.com')."

After googling and searching finally i find out the sollution of it :

Solution : I added a code on my server file 

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://yourUrl.com');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}


app.use(allowCrossDomain); 



Note : Don't forgot to change yourUrl.com with your own.

Chears :)
Happy Coding ..  

Allowing apostrophes(') in a valid email address in codeIgniter

I have recently tried to validate the email of users using CI "Form_validation" Library and have found that using the valid_email it failed quite a few addresses that had apostrophe in their email address such as salman.D'Ahmad@example.com

I already added the apostrophe in there regular expression but still its not validate the email address with apostrophe(') .



Orignal Code:

public function valid_email($str)
{
         return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]                          {2,6}$/ix", $str)) ? FALSE : TRUE;
}


Solution : This is a very small change if you see first by just adding the apostrophe in regex expression but its not working like below :


Change Code:


public function valid_email($str)
{
       return ( ! preg_match("/^([a-z0-9\+_\-']+)(\.[a-z0-9\+_\-']+)*@([a-z0-9\-]+\.)+[a-z]                        {2,6}$/ix", $str)) ? FALSE : TRUE;
}


Final Solution:

public function valid_email($str)
{
$str = str_replace('&#39;', "'", $str);
return ( ! preg_match("/^([A-Za-z0-9\+_\-']+)(\.[A-Za-z0-9\+_\-']+)*@([a-z0-9\-]+\.)+                   [a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}



chears ...
Happy coding :)

List Of Mongo Database Commands And Methods

Below is the list of Mongo Database usefull commands -

1.   use DATABASE   :      The command will create a new database, if it doesn't exist otherwise it will return the existing database.

2.    show dbs             :     To check the list of all your databases.

3.       Your created database (mydb) is not present in list. To display database you need to insert atleast one document into it. Run below command

db.movie.insert({"name":"tutorials point"})

4.       db.dropDatabase() : This will delete the selected database. If you have not selected any database, then it will delete default 'test' database.

5.       createCollection(name, option)  : In the method, name is name of collection to be created. Options is a document and used to specify configuration of collection.

6.       show collections  : You can check the created collection(tables) by using this command.

7.       db.collection_name.drop() : This method is used to drop a collection from the database. drop() method will return true, if the selected collection is dropped successfully otherwise it will return false.

8.       insert() or save()  :

Syntax : db.COLLECTION_NAME.insert(document)

Example :

db.mycol.insert({

   _id: ObjectId(7df78ad8902c),

   title: 'MongoDB Overview',

   description: 'MongoDB is no sql database',

   by: 'tutorials point',

   url: 'http://www.tutorialspoint.com',

   tags: ['mongodb', 'database', 'NoSQL'],

   likes: 100

})


9.   find()  : This method will display all the documents in a non structured way.

Conditions of find() method :

Operation
Syntax
Example
RDBMS Equivalent
Equality
{<key>:<value>}
db.mycol.find({"by":"tutorials point"}).pretty()
where by = 'tutorials point'
Less Than
{<key>:{$lt:<value>}}
db.mycol.find({"likes":{$lt:50}}).pretty()
where likes < 50
Less Than Equals
{<key>:{$lte:<value>}}
db.mycol.find({"likes":{$lte:50}}).pretty()
where likes <= 50
Greater Than
{<key>:{$gt:<value>}}
db.mycol.find({"likes":{$gt:50}}).pretty()
where likes > 50
Greater Than Equals
{<key>:{$gte:<value>}}
db.mycol.find({"likes":{$gte:50}}).pretty()
where likes >= 50
Not Equals
{<key>:{$ne:<value>}}
db.mycol.find({"likes":{$ne:50}}).pretty()
where likes != 



10.   pretty() : To display the results in a formatted way.

11.   AND in MongoDB  :

Syntax : In the find() method if you pass multiple keys by separating them by ',' then MongoDB treats it AND condition. Basic syntax of AND is shown below :

db.mycol.find({key1:value1, key2:value2}).pretty()

Example :

db.mycol.find({"by":"tutorials point","title": "MongoDB Overview"}).pretty()


12.               OR in MongoDB :

Syntax: To query documents based on the OR condition, you need to use $or keyword. Basic syntax of OR is shown below –

db.mycol.find(

   {

      $or: [

         {key1: value1}, {key2:value2}

      ]

   }

).pretty()


Example : db.mycol.find({$or:[{"by":"tutorials point"}, {"title": "MongoDB Overview"}]}).pretty()
 

13.  update()  : This method updates values in the existing document.

Syntax : db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

Example : db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})

Note : By default mongodb will update only single document, to update multiple you need to set a paramter 'multi' to true.

Syntax : db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}},{multi:true})

14.   remove() : This method is used to remove document from the collection. remove()    method accepts two parameters. One is deletion criteria and second is justOne flag –

Syntax : db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

Example : db.mycol.remove({'title':'MongoDB Overview'})

Remove only one : If there are multiple records and you want to delete only first record, then set justOne parameter in remove() method.

Syntax : db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

Remove All documents :  If you don't specify deletion criteria, then mongodb will delete whole documents from the collection. This is equivalent of SQL's truncate command.


Chears :)
Happy Coding