📜  如何使用 Node.js 使用本地/自定义数据库中记录的任何键值对信息查找记录?

📅  最后修改于: 2022-05-13 01:56:23.401000             🧑  作者: Mango

如何使用 Node.js 使用本地/自定义数据库中记录的任何键值对信息查找记录?

自定义数据库表示文件系统中的本地数据库。有两种类型的数据库“SQL”和“NoSQL”。在 SQL 数据库中,数据以表的方式存储,而在 Nosql 数据库中,数据以某种特定的方式独立存储,以独立识别每条记录。我们也可以通过 Nosql 方式在本地创建自己的数据库或数据存储。
有一些步骤涉及创建本地数据库并使用记录的键值对信息从中获取记录。这些步骤如下:

  1. 使用以下命令在项目目录的根目录中创建 package.json 文件:
npm init -y
  1. 使用以下命令安装 express 和 body-parser 包:
npm install express
npm install body-parser
  1. 创建一个 POST 路由以使用键值信息从数据库中请求特定用户。
  2. 将服务器设置为在特定端口上运行(开发人员的端口 - 3000)。
  3. 创建一个存储库文件并添加与创建本地数据库相关的所有逻辑。
  4. 在存储库文件中创建一个方法,以使用键值属性从数据库中获取记录。

注意:如果记录满足所有提供的键值属性,则仅获取记录(返回记录对象),否则如果记录不满足任何属性,则返回空对象。

示例:此示例说明如何使用键值对属性从本地自定义数据库中获取记录。

文件名: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(`
    
           
  `) })   // Route to fetch particular user // information using id app.post('/', async (req, res) => {       // Find user from (id:3f2006d22864b8af)   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({       // The id and email are not belongs     // to same user in such cases no     // records are found     id: '3f2006d22864b8af',     email:'test1.test@gmail.com'   })     res.send(userInfo([user1, user2, user3, user4])) })   // Server setup app.listen(port, () => {   console.log(`Server start on port ${port}`) })


javascript
const displayInfo = (users) => {
    const info = users.map(user => {
        return `
        
          
            
              
            
            
              
            
            
              
            
            
              
            
          

ID :                 ${user.id}

Email :                 ${user.email}

Name :                 ${user.name}

Password :                 ${user.password}

               `     }).join('')     return info } module.exports = {       // Function to displays     // user information     userInfo(users) {         return `                                                                     
                                                                                                                                                                                                                                                        ${displayInfo(users)}                                                   
User1User2User3User4
            
                            `     } }


javascript
// Importing node.js file system,
// crypto module
const fs = require('fs')
const crypto = require('crypto')
 
class Repository {
    constructor(filename) {
 
        // The filename where datas 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 findOneBy(attrs) {
 
        // Read all file contents of
        // the datastore
        const jsonRecords = await
            fs.promises.readFile(this.filename, {
            encoding: 'utf8'
        })
 
        // Parsing json records in javascript
        // object type records
        const records = JSON.parse(jsonRecords)
 
        // Iterating through each record
        for (let record of records) {
            let found = true
 
            // Iterate through each given
            // propert for each record
            for (let key in attrs) {
 
                // If any given property not
                // matches with record record
                // is discarded
                if (record[key] !== attrs[key]) {
                    found = false
                }
            }
            // If 'found' remains true after
            // iterating through each given
            // property that means record found
            if (found) {
                return record
            }
        }
 
        // If record not found
        return {}
    }
}
 
// The 'datastore.json' file created
// at runtime if it not exist here we
// try to fetch information from
// database using some properties
// that means database(datastore.json)
// already exist and there are also
// records in it.
module.exports = new Repository('datastore.json')


文件名:fetchUser.js这个js文件有一个方法可以将获取的用户信息显示到网页上。

javascript

const displayInfo = (users) => {
    const info = users.map(user => {
        return `
        
          
            
              
            
            
              
            
            
              
            
            
              
            
          

ID :                 ${user.id}

Email :                 ${user.email}

Name :                 ${user.name}

Password :                 ${user.password}

               `     }).join('')     return info } module.exports = {       // Function to displays     // user information     userInfo(users) {         return `                                                                     
                                                                                                                                                                                                                                                        ${displayInfo(users)}                                                   
User1User2User3User4
            
                            `     } }

文件名:repository.js此文件包含使用键值信息查找记录的所有逻辑。

javascript

// Importing node.js file system,
// crypto module
const fs = require('fs')
const crypto = require('crypto')
 
class Repository {
    constructor(filename) {
 
        // The filename where datas 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 findOneBy(attrs) {
 
        // Read all file contents of
        // the datastore
        const jsonRecords = await
            fs.promises.readFile(this.filename, {
            encoding: 'utf8'
        })
 
        // Parsing json records in javascript
        // object type records
        const records = JSON.parse(jsonRecords)
 
        // Iterating through each record
        for (let record of records) {
            let found = true
 
            // Iterate through each given
            // propert for each record
            for (let key in attrs) {
 
                // If any given property not
                // matches with record record
                // is discarded
                if (record[key] !== attrs[key]) {
                    found = false
                }
            }
            // If 'found' remains true after
            // iterating through each given
            // property that means record found
            if (found) {
                return record
            }
        }
 
        // If record not found
        return {}
    }
}
 
// The 'datastore.json' file created
// at runtime if it not exist here we
// try to fetch information from
// database using some properties
// that means database(datastore.json)
// already exist and there are also
// records in it.
module.exports = new Repository('datastore.json')

文件名:Package.json

包.json 文件

数据库

数据库:

使用以下命令运行index.js文件:

node index.js

输出:

输出画面

点击按钮后

点击按钮后的输出画面

注意:第一次运行程序数据库(datastore.json)文件在项目目录下不存在。它在运行程序后动态创建。但是这里我们尝试使用键值对信息从数据库中获取信息,这意味着程序假设已经运行了一次,并且一些记录被添加到我们尝试获取的数据库中。