How to delete a record from your local/custom database in Node.js ?
Last Updated : 22 Jul, 2020
Comments
Improve
Suggest changes
1 Like
Like
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 filejavascript
constexpress=require('express')constrepo=require('./repository')constshowRecordTemplet=require('./showRecord')constapp=express()constport=process.env.PORT||3000// Home pageapp.get('/',async(req,res)=>{constrecords=awaitrepo.getAllRecords()res.send(showRecordTemplet(records))})// Post route to delete recordapp.post('/delete/:id',async(req,res)=>{constid=req.params.idconsttemp=awaitrepo.delete(id)res.redirect('/')})// Server setupapp.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.
javascript
// Importing node.js file system, crypto module constfs=require('fs')classRepository{constructor(filename){// The filename where datas are// going to storeif(!filename){thrownewError('Filename is required to create a datastore!')}this.filename=filenametry{fs.accessSync(this.filename)}catch(err){// If file not exist it is created// with empty arrayfs.writeFileSync(this.filename,'[]')}}// Method to fetch all recordsasyncgetAllRecords(){returnJSON.parse(awaitfs.promises.readFile(this.filename,{encoding:'utf8'}))}// Delete Methodasyncdelete(id){// Read all file contents of // the datastoreconstjsonRecords=awaitfs.promises.readFile(this.filename,{encoding:'utf8'})// Parsing json records in javascript// object type recordsconstrecords=JSON.parse(jsonRecords)// Filter RecordsconstfilteredRecords=records.filter(record=>record.id!==id)// Write all records back to the // custom databaseawaitfs.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=newRepository('datastore.json')
Filename: showRecord.js javascript
module.exports=records=>{constdisplayRecordId=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 filepackage.json file
Run index.js file using the following command:
node index.js
Output:
Database:
Database before deleteDatabase after deleteNote: 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.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.