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: fetchUser.js This js file has a method to display fetched user information to webpage.
Filename: repository.js This file contains all the logic to find a record using key-value information.
Run index.js file using the following command:
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.