📌  相关文章
📜  如何在 Node.js 中为本地/自定义数据库中的每条记录添加唯一 ID?

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

如何在 Node.js 中为本地/自定义数据库中的每条记录添加唯一 ID?

自定义数据库表示文件系统中的本地数据库。有两种类型的数据库“SQL”和“NoSQL”。在 SQL 数据库中,数据以表格方式存储,而在 Nosql 数据库中,数据以某种特定的方式独立存储,以独立识别每条记录。我们也可以通过 Nosql 方式在本地创建自己的数据库或数据存储。要以 NoSQL 方式存储信息,我们必须为每条记录添加唯一的 Id,以便可以独立识别每条记录。

有一些步骤涉及创建本地数据库并向其添加具有唯一 ID 的记录。这些步骤如下:

  • 在项目目录的根目录下创建 package.json 文件。
    创建 package.json 文件的命令
    npm init -y
  • 安装 express 和 body-parser 包。
    安装包的命令
    npm install express body-parser
  • 创建一个 GET 路由以显示表单(将信息提交到数据库的 HTML 表单)。
  • 创建后续的 post 路由来处理表单提交请求。
  • 将服务器设置为在特定端口上运行(开发人员的端口 - 3000)。
  • 创建一个存储库文件并添加与创建本地数据库相关的所有逻辑。
  • 在存储库文件中创建一个方法,为每条记录添加一个唯一的字母数字 ID。
  • 在存储库文件中创建一个方法,以将每个唯一记录以 json 格式添加到数据库中。

此示例说明如何创建本地数据库并使用唯一 ID 向其中添加记录。

文件名:index.js

const express = require('express')
const bodyParser = require('body-parser')
const repo = require('./repository')
  
const app = express()
  
const port = process.env.PORT || 3000
  
// The body-parser middleware 
// to parse form data
app.use(bodyParser.urlencoded({extended : true}))
  
// Get route to display HTML form
app.get('/signup', (req, res) => {
  res.send(`
    
     
       
         
                     
                   
              
         
                     
                 
          
                 
     
    
     `) });    // Post route to handle form submission // logic and add data to the database app.post('/signup', async (req, res) => {   const {email, password} = req.body      const addedRecord = await      repo.createNewRecord({email, password})      console.log(`Added Record :      ${JSON.stringify(addedRecord, null, 4)}`)        res.send("Information added to the "         + "database successfully.") })    // Server setup app.listen(port, () => {   console.log(`Server start on port ${port}`) })

文件名:repository.js

// Importing node.js file system, crypto module 
const fs = require('fs')
const crypto = require('crypto')
  
class Repository {
  
  constructor(filename) {
      
    // 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, '[]')
    }
  }
  
  // Logic to add data or record
  async createNewRecord(attributes) {
      
    // Assign unique Id to each record
    attributes.id = this.generateUniqueID()
  
    // Read 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)
  
    // Adding new record
    objRecord.push(attributes)
  
    // Writing all records back to the file
    await fs.promises.writeFile(
      this.filename,
      JSON.stringify(objRecord, null, 2)   
    )
  
    return attributes;
  }
  
  // Method to generate unique ID 
  generateUniqueID() {
    return crypto.randomBytes(8).toString('hex')
  }
}
  
// The 'datastore.json' file created at runtime 
// and all the information provided via signup
// form store in this file in JSON format.
module.exports = new Repository('datastore.json')

包.json 文件:

运行此程序的步骤
使用以下命令运行 index.js 文件:

node index.js

提交回复的表格:
注意:这里三个响应依次提交,所有响应都存储在 datastore.json 文件中。

提交请求后重定向页面:

输出:

数据库:

注意:第一次运行程序的数据库(datastore.json)文件在项目目录下不存在,运行程序后动态创建并存储提交的响应。之后,所有提交的响应都会被一一追加到数据库中。