How to Generate Fake Data for an Application using Faker.js

Introduction 
 
What is faker.js?
 
- Faker.js is a javascript library for generating fake data. 
- Fake data is useful when building and testing our application.
- The faker.js can generate fake data for various areas, including address, name, email, product, etc.
- For more details, visit faker.js.

Project Structure 
 
|----------- app.js
|
|--------- models
|                   |---------- user.js
|--------- views
                    |---------- home.ejs 
 
 
 
 
How to set up the Project Folder 
 
1. Open console/terminal and type mkdir followed by the folder name you want to give.
2. Change to the new folder by typing cd folder name.
 
 
 
Setup Node For The Project
 
1. Type npm init on console/terminal.
2. The npm init will create a package.json file
3. The package.json will look like this:
 
 
 
4. Now we will install the packages for our project using npm install followed by package names we want to install.
5. The following packages will be installed: express ejs faker mongoose.
 
 
6. This will generate a folder name node_modules which will contain all the node packages.
7. After the package installation, the package.json will look like this:
 
 
 
8. Now add a new file named app.js.
9. Go back to package.json file, and in scripts write start :app.js.
10. This will be the application entry point.
 
 
 
11. Make new folders views and models.
12. In views add a file home.ejs.
13. Here, we are using .ejs extension for views file because the template engine is ejs.
14. Add a file user.js.
15. User.js will contain the collection (table) schema.
 
 
Models
  1. var mongoose = require('mongoose')  
  2.   
  3. var fakerSchema =  new mongoose.Schema({  
  4.     firstname: String,  
  5.     lastname:String,  
  6.     phonenumber:String,  
  7.     city:String,  
  8.     state:String,  
  9.     country:String  
  10. });  
  11.   
  12. module.exports = mongoose.model('fakeCollection',fakerSchema);  
  • mongoose.Schema({}) - contains the fields of our collection(table).    
  • mongoose.model() - contains collection(table) name and the object containing collection(table) the field data.
  • fakeCollection is the collection(table) name.
  • module.exports - makesthis module accessible in other module/files. We have to export it using this.

app.js
  1. var express     = require('express');  
  2. var faker       = require('faker');  
  3. var mongoose    = require('mongoose');  
  4. var path        = require('path');  
  5. var fakerModel = require('./models/user');  
  6.   
  7. mongoose.connect('mongodb://localhost:27017/fakerdata',{useNewUrlParser:true})  
  8. .then(()=>console.log('connected')).catch(err=>console.log('error occured',err));  
  9.   
  10. var app = express();  
  11.   
  12. app.set('view engine','ejs');  
  13. app.set("views",path.resolve(__dirname,'views'));  
  14.   
  15. app.get('/',(req,res)=>{  
  16.   fakerModel.find((err,data)=>{  
  17.       console.log('dvb',data)  
  18.       if(err){  
  19.           console.log('erer',err)  
  20.       }  
  21.       else if(data){  
  22.           console.log('havr data',data)  
  23.         res.render('home',{data:data})    
  24.       }  
  25.       else{  
  26.         console.log('dont havr data',data)  
  27.         res.render('home',{data:{}})    
  28.       }  
  29.   })     
  30. })  
  31.   
  32.   
  33. app.post('/',(req,res)=>{  
  34.       for(var i=0; i<10;i++){  
  35.         var fakke = new fakerModel({  
  36.         firstname:faker.name.firstName(),  
  37.         lastname:faker.name.lastName(),  
  38.         phonenumber:faker.phone.phoneNumber(),  
  39.         city:faker.address.city(),  
  40.         state:faker.address.state(),  
  41.         country:faker.address.country()  
  42.           })  
  43.           fakke.save((err,data)=>{  
  44.                if(err){
  45.               console.log('error occured',err)  
  46.               }
  47.           })  
  48.       }  
  49.       res.redirect('/');  
  50.     })  
  51.   
  52.   
  53. var port = process.env.PORT || 3000;  
  54.   
  55. app.listen(port,()=>console.log(`server running at ${port}`))  
  56.   
  57. module.exports=app;  

  • mongoose.connect() - will set up the connection with local db on our system.
  • localhost:27017/fakerdata - fakerdata is the name of our database which will be created on server when we insert data into it.
  • app.set("views",path.resolve(__dirname,"views")) - this tell express where the views folder is.
  • app.set("view engine","ejs") - this tells express that any file ending in .ejs should be rendered with ejs packages.
  • Using faker object we will access the faker API method().
  • We are using for loop for inserting 10 fake records in our collection.
  • The faker API method we using for fake data is firstname, lastname, phonenumber, city, state, country.
     
    Views 
    • home.ejs 
    1. <html lang="en">  
    2. <head>  
    3.     <meta charset="UTF-8">  
    4.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    5.     <meta http-equiv="X-UA-Compatible" content="ie=edge">  
    6.     <title>Document</title>  
    7. </head>  
    8. <body>  
    9.     <form action="/" method="POST">  
    10.    <input type="submit" value="click to insert data">   
    11.   </form>  
    12.   
    13.   <% if(data.length >0) {%>  
    14.      <table border="1" style="text-align:center">  
    15.          <thead>  
    16.              <tr>  
    17.                  <th>  
    18.                      firstname  
    19.                  </th>  
    20.                  <th>  
    21.                      lastname  
    22.                  </th>  
    23.                  <th>  
    24.                      phonenumber  
    25.                  </th>  
    26.                  <th>  
    27.                      city  
    28.                  </th>  
    29.                  <th>  
    30.                    state  
    31.                </th>  
    32.                <th>  
    33.                    country  
    34.                </th>  
    35.              </tr>  
    36.          </thead>  
    37.          <tbody>  
    38.              <% for(var i=0; i< data.length; i++) {%>  
    39.              <tr>  
    40.                  <td>  
    41.                    <%= data[i].firstname%>    
    42.                  </td>  
    43.                  <td>  
    44.                    <%= data[i].lastname%>    
    45.                  </td>  
    46.                  <td>  
    47.                    <%= data[i].phonenumber%>    
    48.                  </td>  
    49.                  <td>  
    50.                    <%= data[i].city%>    
    51.                  </td>  
    52.                  <td>  
    53.                    <%= data[i].state%>    
    54.                  </td>  
    55.                  <td>  
    56.                    <%= data[i].country%>    
    57.                  </td>  
    58.              </tr>  
    59.              <% } %>  
    60.          </tbody>  
    61.      </table>  
    62.    <% } %>  
    63. </body>  
    64. </html>