Express 有第三方链接数据库的中间件,但是因为中间件使用的是依赖注入,就没有编辑器提示,所以更好的方式是使用单例模式,引入模块的方式来实现 Express 连接数据库。
Node.js 有很多 ORM 模块方便我们操作数据库
这里我们使用 Prisma 来连接 SQLite
Prisma 初始化 1 2 npm i --save prisma@latest npm i --save @prisma/client@latest
初始化 prisma 项目
运行后将会在根目录下生成一个prisma/schema.prisma
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 // This is your Prisma schema file, // learn more about it in the docs: https://pris.ly/d/prisma-schema generator client { provider = "prisma-client-js" output = "../.prisma-client" // 将客户端代码生成到根目录下并在 git 中忽略 } datasource db { provider = "sqlite" url = "file:db/database.db" // 当前文件夹下的 db/database.db } /// 用户表 model user { /// The ID of the user id String @id @default(cuid()) /// The name of the user nickname String? /// The email of the user email String? /// The password of the user password String? /// The phone number of the user phone String? /// The account of the user account String? /// createdAt createdAt DateTime @default(now()) /// updatedAt updatedAt DateTime @default(now()) @updatedAt() @@unique([email]) @@unique([phone]) @@unique([account]) @@index([email, password]) @@index([phone, password]) @@index([account, password]) }
单例模式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 const { PrismaClient } = require ("../../.prisma-client" );class Prisma { static init ( ) { if (!this .instance ) { this .instance = new PrismaClient (); } return this .instance ; } }module .exports = Prisma .init ();
使用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 const express = require ("express" );const router = express.Router ();const prisma = require ("../../../utils/prisma" ); router.post ("" , async function (req, res, next ) { try { const { email, password } = req.body ; const users = await prisma.users .findFirst ({ where : { email, password : await md5Slat (password) }, select : { id : true , name : true , email : true , create_time : true } }); } catch (error) { next (error); } });
npm 脚本配置 1 2 3 4 5 6 7 8 "scripts" : { "start" : "node ./bin/www" , "dev" : "npm run pgs && nodemon ./bin/www" , "p.gs" : "prisma generate" , "p.updb" : "prisma migrate dev" , "p.s" : "prisma studio" , "lint" : "eslint --fix ." }
gitignore 配置 因为使用的是 SQLite ,数据库在本地,所以想忽略掉本地数据库。且客户端代码也不提交代 git 中,运行前生成就行。
1 2 3 # prisma .prisma-client prisma/db