How to delete a record from your local/custom database in Node.js ?
Last Updated :
22 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 create, delete information of it. These steps are as follows:
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
app.get( '/' , async (req, res) => {
const records = await repo.getAllRecords()
res.send(showRecordTemplet(records))
})
app.post( '/delete/:id' , async (req, res) => {
const id = req.params.id
const temp = await repo. delete (id)
res.redirect( '/' )
})
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.
const fs = require( 'fs' )
class Repository {
constructor(filename) {
if (!filename) {
throw new Error(
'Filename is required to create a datastore!' )
}
this .filename = filename
try {
fs.accessSync( this .filename)
} catch (err) {
fs.writeFileSync( this .filename, '[]' )
}
}
async getAllRecords() {
return JSON.parse(
await fs.promises.readFile( this .filename, {
encoding: 'utf8'
})
)
}
async delete (id) {
const jsonRecords = await
fs.promises.readFile( this .filename, {
encoding: 'utf8'
})
const records = JSON.parse(jsonRecords)
const filteredRecords = records.filter(
record => record.id !== id)
await fs.promises.writeFile(
this .filename,
JSON.stringify(filteredRecords, null , 2)
)
}
}
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
Share your thoughts in the comments
Please Login to comment...