How to update a record in your local/custom database in Node.js?
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:
- 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 express
npm install body-parser
- Create a POST route to request for particular user database 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 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
app.use(bodyParser.urlencoded({extended : true }))
app.get( '/' , (req, res) => {
const id = '32b3a9f5d8f33a8d'
res.send(`
<form method= 'GET' action= './update/${id}' >
<button>Update Record</button>
</form>
`)
})
app.get( '/update/:id' , async (req, res) => {
const id = req.params.id
const temp = await (updateTemplet({id}))
res.send(temp)
})
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' )
})
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.
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 findById(id) {
const jsonRecords = await
fs.promises.readFile( this .filename, {
encoding: 'utf8'
})
const objRecord = JSON.parse(jsonRecords)
const requiredRecord = objRecord
.find(record => record.id === id)
return requiredRecord
}
async update(id, attrs) {
const jsonRecords = await
fs.promises.readFile( this .filename, {
encoding: 'utf8'
})
const records = JSON.parse(jsonRecords)
const record = records.find(
eachRecord => eachRecord.id === id)
if (!record) {
throw new Error(`Id '${id}' not found`)
}
Object.assign(record, attrs)
await fs.promises.writeFile(
this .filename,
JSON.stringify(records, null , 2)
)
return record
}
}
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.
Last Updated :
18 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...