Skip to content
Related Articles

Related Articles

How to find record using any key-value pair information of record in your local/custom database using Node.js ?
  • Last Updated : 18 Jul, 2020

The custom database signifies the local database in your file system. There are two types of database ‘SQL’ and ‘NoSQL’. In SQL database data are stored as table manner and in Nosql database data are stored independently with some particular way to identify each record independently. We can also create our own database or datastore locally in Nosql manner.

There are some steps involve in creating the local database and fetch records from it using key-value pair information of record. These steps are as follows:

  1. Create package.json file in the root of the project directory using the following command:
    npm init -y
  2. Install express and body-parser package using the following command:
    npm install express
    npm install body-parser
    
  3. Create a POST route to request for a particular user from database using key-value information.
  4. Set the server to run on a specific port(Developer’s port – 3000).
  5. Create a repository file and add all the logic related to creating a local database.
  6. Create a method in the repository file to fetch a record from the database using key-value properties.

Note: If a record satisfied all the provided key-value properties then only the record is fetched(record object is returned) otherwise if any of the properties are not satisfied by the record then an empty object is returned.

Example: This example illustrates how to fetch a record from a local custom database using key-value pair properties.

Filename: index.js






const express = require('express')
const repo = require('./repository')
const {userInfo} = require('./fetchUser')
  
const app = express()
  
const port = process.env.PORT || 3000
  
app.get('/', (req, res) => {
  res.send(`
    <form method='POST'>
      <button>Fetch User Information</button>
    </form>
  `)
})
  
// Route to fetch particular user
// information using id
app.post('/', async (req, res) => {
    
  // Find user from (id:3f2006d22864b8af)
  const user1 = await repo.findOneBy({
      name:'Test2Test',
      email: 'test2.test@gmail.com'
  })
  
  const user2 = await repo.findOneBy({
    email: 'test1.test@gmail.com'
  })
  
  const user3 = await repo.findOneBy({
    id: '3f2006d22864b8af'
  })
  
  const user4 = await repo.findOneBy({
  
    // The id and email are not belongs
    // to same user in such cases no 
    // records are found
    id: '3f2006d22864b8af',
    email:'test1.test@gmail.com'
  })
  
  res.send(userInfo([user1, user2, user3, user4]))
})
  
// Server setup
app.listen(port, () => {
  console.log(`Server start on port ${port}`)
})

Filename: fetchUser.js This js file has a method to display fetched user information to webpage.




const displayInfo = (users) => {
    const info = users.map(user => {
        return `
        <td>
          <table>
            <tr>
              <td><p><strong>ID : 
                </strong>${user.id}</p></td>
            </tr>
            <tr>
              <td><p><strong>Email : 
                </strong>${user.email}</p></td>
            </tr>
            <tr>
              <td><p><strong>Name : 
                </strong>${user.name}</p></td>
            </tr>
            <tr>
              <td><p><strong>Password : 
                </strong>${user.password}</p></td>
            </tr>
          </table>
        </td>
      `
    }).join('')
    return info
}
module.exports = {
  
    // Function to displays 
    // user infomation
    userInfo(users) {
        return `
        <html>
          <head>
            <link rel ='stylesheet'
          </head>
          <body>
            <div class='container'>
              <table class='table'>
                <thead>
                  <tr>
                    <th>User1</th>
                    <th>User2</th>
                    <th>User3</th>
                    <th>User4</th>
                  </tr>
                     
                </thead>
                <tbody>
                  <tr>
                    ${displayInfo(users)}
                  </tr>
                </tbody>
              </table>
            </div>  
          </body>
        </html>
      `
    }
}

Filename: repository.js This file contains all the logic to find a record using key-value information.




// Importing node.js file system,
// crypto module 
const fs = require('fs')
const crypto = require('crypto')
  
class Repository {
    constructor(filename) {
  
        // The filename where datas are
        // going to store
        if (!filename) {
            throw new Error('Filename is '
                + 'required to create a datastore!')
        }
        this.filename = filename
        try {
            fs.accessSync(this.filename)
        } catch (err) {
  
            // If file not exist, It is 
            // created with empty array
            fs.writeFileSync(this.filename, '[]')
        }
    }
  
    async findOneBy(attrs) {
  
        // Read all file contents of
        // the datastore
        const jsonRecords = await 
            fs.promises.readFile(this.filename, {
            encoding: 'utf8'
        })
  
        // Parsing json records in javascript 
        // object type records
        const records = JSON.parse(jsonRecords)
  
        // Iterating through each record
        for (let record of records) {
            let found = true
  
            // Iterate through each given
            // propert for each record
            for (let key in attrs) {
  
                // If any given property not 
                // matches with record record
                // is discarded
                if (record[key] !== attrs[key]) {
                    found = false
                }
            }
            // If 'found' remains true after
            // iterating through each given
            // property that means record found 
            if (found) {
                return record
            }
        }
  
        // If record not found
        return {}
    }
}
  
// The 'datastore.json' file created
// at runtime if it not exist here we
// try to fetch information from 
// database using some properties 
// that means database(datastore.json) 
// already exist and there are also
// records in it.
module.exports = new Repository('datastore.json')

Filename: Package.json

package.json file

Database

Database:

Run index.js file using the following command:

node index.js

Output:

Output screen

After Clicking the button

Output screen after clicking the button

Note: For the first time running the program database(datastore.json) file not exist in the project directory. It created dynamically after running the program. But here we try to fetch information from the database using key-value pair information that means program suppose to have already run once and some records are added into the database that we try to fetch.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :