Skip to content
Related Articles

Related Articles

Improve Article

How to update a record in your local/custom database in Node.js?

  • Last Updated : 18 Jul, 2020
Geek Week

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 create, find, update information of it. These steps are as follows:

  1. Create package.json file in root of 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 particular user database using id.
  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 local database.
  6. Create a method in repository file to update a record from database using id.

Example: This example illustrates how to update a record in a local custom database.

Filename: index.js




const express = require('express')
const bodyParser = require('body-parser')
  
const repo = require('./repository')
const updateTemplet = require('./updateRecordForm')
  
const app = express()
const port = process.env.PORT || 3000
  
// The body-parser middleware to parse form data
app.use(bodyParser.urlencoded({extended : true}))
  
// Home page
app.get('/', (req, res) => {
  const id = '32b3a9f5d8f33a8d'
  res.send(`
    <form method='GET' action='./update/${id}'>
      <button>Update Record</button>
    </form>
  `)
})
  
// Get route to show update form
app.get('/update/:id', async (req, res) => {
  const id = req.params.id
  const temp = await (updateTemplet({id}))
  res.send(temp)
})
  
// Post route to update record
app.post('/update/:id', async (req, res) => {
  const id = req.params.id
  const record = await repo.update(id, req.body)
  console.log(`Record Updated : 
    \n${JSON.stringify(record, null, 2)}`)
  res.send('Record Updated')
})
  
// Server setup
app.listen(port, () => {
  console.log(`Server start on port ${port}`)
})

Filename: repository.js This file contains all the logic to update a record of custom database.






// Importing node.js file system, crypto module 
const fs = require('fs')
  
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, '[]')
        }
    }
  
    // The findById method used in the example
    async findById(id) {
  
        // Read all filecontents of the datastore
        const jsonRecords = await 
            fs.promises.readFile(this.filename, {
            encoding: 'utf8'
        })
  
        // Parsing JSON records in javascript
        // object type records
        const objRecord = JSON.parse(jsonRecords)
  
        // Search for required record
        const requiredRecord = objRecord
            .find(record => record.id === id)
        return requiredRecord
    }
  
    // Update Method
    async update(id, 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)
  
        // Find target record to update with id
        const record = records.find(
            eachRecord => eachRecord.id === id)
  
        // If given id not belongs to any
        // record in database
        if (!record) {
            throw new Error(`Id '${id}' not found`)
        }
  
        // Update record
        Object.assign(record, attrs)
  
        // Write all records back to the
        // custom database
        await fs.promises.writeFile(
            this.filename,
            JSON.stringify(records, null, 2)
        )
        return record
    }
}
  
// The 'datastore.json' file created at
// runtime if it not exist,  here we try
// to update information of database 
// that means database(datastore.json)
// already exist and there are also
// records in it.
module.exports = new Repository('datastore.json')

Filename: updateRecordForm.js




const repo = require('./repository')
module.exports = async ({ id }) => {
    const record = await repo.findById(id)
    return `
    <div>
      <form method='POST'>
        <div>
          <div>
            <label id='email'>Username</label>
          </div>
          <input type='text' name='email' 
            value=${record.email} for='email'>
        </div>
        <div>
          <div>
            <label id='password'>Password</label>
          </div>
          <input type='password' name='password' 
            value=${record.password} 
          for='password'>
        </div>
        <div>
          <div>
            <label id='name'>Name</label>
          </div>
          <input type='text' name='name' 
            value=${record.name} for='name'>
        </div>
          <button>Update</button>
        </div>
      </form>
  </div>
  `
}

Filename: package.json

package.json file

Run index.js file using the following command:

node index.js

Output:

Output screen before click

Output screen after click

Updating Record

After update output screen

Database:

Database before update

Database after update

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 update a record in the database that means program suppose to have already run once and some records are added into the database that we try to update.




My Personal Notes arrow_drop_up
Recommended Articles
Page :