How to find record using any key-value pair information of record in your local/custom database using 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 fetch records from it using key-value pair information of record. These steps are as follows:
- Create package.json file in the root of the 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 a particular user from database using key-value information.
- 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 a local database.
- Create a method in the repository file to fetch a record from the database using key-value properties.
Note: If a record satisfied all the provided key-value properties then only the record is fetched(record object is returned) otherwise if any of the properties are not satisfied by the record then an empty object is returned.
Example: This example illustrates how to fetch a record from a local custom database using key-value pair properties.
Filename: index.js
javascript
const express = require( 'express' )
const repo = require( './repository' )
const {userInfo} = require( './fetchUser' )
const app = express()
const port = process.env.PORT || 3000
app.get( '/' , (req, res) => {
res.send(`
<form method= 'POST' >
<button>Fetch User Information</button>
</form>
`)
})
app.post( '/' , async (req, res) => {
const user1 = await repo.findOneBy({
name: 'Test2Test' ,
email: 'test2.test@gmail.com'
})
const user2 = await repo.findOneBy({
email: 'test1.test@gmail.com'
})
const user3 = await repo.findOneBy({
id: '3f2006d22864b8af'
})
const user4 = await repo.findOneBy({
id: '3f2006d22864b8af' ,
email: 'test1.test@gmail.com'
})
res.send(userInfo([user1, user2, user3, user4]))
})
app.listen(port, () => {
console.log(`Server start on port ${port}`)
})
|
Filename: fetchUser.js This js file has a method to display fetched user information to webpage.
javascript
const displayInfo = (users) => {
const info = users.map(user => {
return `
<td>
<table>
<tr>
<td>
<p><strong>ID :
</strong>${user.id}</p>
</td>
</tr>
<tr>
<td>
<p><strong>Email :
</strong>${user.email}</p>
</td>
</tr>
<tr>
<td>
<p><strong>Name :
</strong>${user.name}</p>
</td>
</tr>
<tr>
<td>
<p><strong>Password :
</strong>${user.password}</p>
</td>
</tr>
</table>
</td>
`
}).join( '' )
return info
}
module.exports = {
userInfo(users) {
return `
<html>
<head>
<link rel = 'stylesheet'
</head>
<body>
<div class= 'container' >
<table class= 'table' >
<thead>
<tr>
<th>User1</th>
<th>User2</th>
<th>User3</th>
<th>User4</th>
</tr>
</thead>
<tbody>
<tr>
${displayInfo(users)}
</tr>
</tbody>
</table>
</div>
</body>
</html>
`
}
}
|
Filename: repository.js This file contains all the logic to find a record using key-value information.
javascript
const fs = require( 'fs' )
const crypto = require( 'crypto' )
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 findOneBy(attrs) {
const jsonRecords = await
fs.promises.readFile( this .filename, {
encoding: 'utf8'
})
const records = JSON.parse(jsonRecords)
for (let record of records) {
let found = true
for (let key in attrs) {
if (record[key] !== attrs[key]) {
found = false
}
}
if (found) {
return record
}
}
return {}
}
}
module.exports = new Repository( 'datastore.json' )
|
Filename: Package.json
package.json file
Database
Database:
Run index.js file using the following command:
node index.js
Output:
Output screen
After Clicking the button
Output screen after clicking the button
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 fetch information from the database using key-value pair information that means program suppose to have already run once and some records are added into the database that we try to fetch.
Last Updated :
08 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...