How to find record by Id from local/custom database in Node.js ? - GeeksforGeeks

14 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 fetch records from it using id. These steps are as follows:
Create package.json file in the root of the project directory.Command to create package.json filenpm init -y
npm init -y
Install express and body-parser package.Command to install packagesnpm install express
npm install express
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 fetch a record from database using id.
Example 1: This example illustrates how to fetch a record from a local custom database using an id.Filename: index.js
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>  `)})  // Route to fetch particular user // information using idapp.post('/', async (req, res) => {      // Find user from (id:3f2006d22864b8af)  const user =     await repo.findById('3f2006d22864b8af')    res.send(userInfo(user))})  // Server set to runapp.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.
module.exports = {    // Function to displays user information  userInfo(user) {    return `      <div>        <p><strong>ID : </strong>${user.id}<p>      </div>      <div>        <p><strong>Email : </strong>${user.email}<p>      </div>      <div>        <p><strong>Name : </strong>${user.name}<p>      </div>      <div>        <p><strong>Password : </strong>${user.password}<p>      </div>         `  }}
Filename: repository.js This file contains all the logic to find a record using an id.
// Importing node.js file system module const fs = require('fs')  class Repository {  constructor(filename) {      // Filename where data 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, '[]')    }  }    async findById(id){      // Read all filecontents of the datastore    const jsonRecords = await         fs.promises.readFile(this.filename, {      encoding : 'utf8'    })      // Parsing JSON records in JavaScript    // object type records    const objRecord = JSON.parse(jsonRecords)      // Search for required record    const requiredRecord =       objRecord.find(record => record.id === id)    return requiredRecord  }}  // 'datastore.json' file created at runtime// if it does not exist. Here we try to fetch// information from database using an id that// means database(datastore.json) already exist// and there are also records in it.module.exports = new Repository('datastore.json')
Package.json file:
Database:
Output:
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 an id that means program suppose to have already run once and some records are added into the database that we try to fetch.
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Difference between npm i and npm ci in Node.js
Mongoose Populate() Method
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Convert a string to an integer in JavaScript