Skip to content
Related Articles
Open in App
Not now

Related Articles

How to find record using any key-value pair information of record in your local/custom database using Node.js ?

Improve Article
Save Article
  • Last Updated : 08 Oct, 2021
Improve Article
Save Article

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
  1. Install express and body-parser package using the following command: 
npm install express
npm install body-parser
  1. Create a POST route to request for a particular user from database using key-value information.
  2. Set the server to run on a specific port(Developer’s port – 3000).
  3. Create a repository file and add all the logic related to creating a local database.
  4. 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) => {
    <form method='POST'>
      <button>Fetch User Information</button>
// Route to fetch particular user
// information using id'/', async (req, res) => {
  // Find user from (id:3f2006d22864b8af)
  const user1 = await repo.findOneBy({
      email: ''
  const user2 = await repo.findOneBy({
    email: ''
  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',
  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 = => {
        return `
<p><strong>ID :
<p><strong>Email :
<p><strong>Name :
<p><strong>Password :
    return info
module.exports = {
    // Function to displays
    // user information
    userInfo(users) {
        return `
            <link rel ='stylesheet'
            <div class='container'>
              <table class='table'>

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 {
        } 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





Run index.js file using the following command: 

node index.js




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.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!