Open In App

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

Last Updated : 22 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Create package.json file in root of project directory using the following command:
    npm init -y
  • Install express and body-parser package using the following command:
    npm install body-parser
    npm install express
  • Create a POST route to delete a particular user record using id.
  • Set the server to run on a specific port(Developer’s port – 3000).
  • Create a repository file and add all the logic related to creating local database.
  • Create a method in repository file to delete a record from database using id.

Example: This example illustrates how to delete a record from a local custom database.

Filename: index.js file




const express = require('express')
const repo = require('./repository')
const showRecordTemplet = require('./showRecord')
  
const app = express()
const port = process.env.PORT || 3000
  
// Home page
app.get('/', async (req, res) => {
  const records = await repo.getAllRecords()
  res.send(showRecordTemplet(records))
})
  
// Post route to delete record
app.post('/delete/:id', async (req, res) => {
  const id = req.params.id
  const temp = await repo.delete(id)
  res.redirect('/')
})
  
// Server setup
app.listen(port, () => {
  console.log(`Server start on port ${port}`)
})


Filename: repository.js file This file contains all the logic to delete 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, '[]')
        }
    }
  
    // Method to fetch all records
    async getAllRecords() {
        return JSON.parse(
            await fs.promises.readFile(this.filename, {
                encoding: 'utf8'
            })
        )
    }
  
    // Delete Method
    async delete(id) {
  
        // 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)
  
        // Filter Records
        const filteredRecords = records.filter(
                    record => record.id !== id)
  
        // Write all records back to the 
        // custom database
        await fs.promises.writeFile(
            this.filename,
            JSON.stringify(filteredRecords, null, 2)
        )
    }
}
  
// The 'datastore.json' file created at runtime
// if it not exist, here we try to delete 
// information from database that means 
// database(datastore.json) already exist
// and there are also records in it.
module.exports = new Repository('datastore.json')


Filename: showRecord.js




module.exports = records => {
  const displayRecordId = records.map(record => {
    return `
    <p>
      Record ID - <strong>${record.id}</strong>
      <form action='delete/${record.id}' method='POST'>
        <button>Delete Record</button>
      </form>
    </p> 
    `
  }).join('')
  
  return `
    <div>
      ${displayRecordId}
    </div>
  `
}


Filename: package.json file

package.json file

Run index.js file using the following command:

node index.js

Output:

Database:

Database before delete

Database after delete

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads