本文最后更新于:2024年4月25日 上午
前提
已安装MongoDB
安装依赖
1 2
| pnpm i mongodb pnpm i mongoose
|
目录
src
目录下新建mongo
目录,models
目录存放各表,index.ts
用于链接数据库
小插曲
运行时8080
端口被占用报错
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| [nodemon] starting `ts-node ./src/app.ts` [nodemon] spawning [nodemon] child pid: 13308 Error: listen EADDRINUSE: address already in use :::8080 at Server.setupListenHandle [as _listen2] (node:net:1330:16) at listenInCluster (node:net:1378:12) at Function.listen (F:\vue3博客\vue3BlogBackend\node_modules\.pnpm\registry.npmmirror.com+express@4.17.3\node_modules\express\lib\application.js:618:24) at Object.<anonymous> (F:\vue3博客\vue3BlogBackend\src\app.ts:16:5) at Module._compile (node:internal/modules/cjs/loader:1103:14) at Module.m._compile (A:\node_modules\.pnpm\registry.npmmirror.com+ts-node@10.7.0_typescript@4.6.3\node_modules\ts-node\src\index.ts:1455:23) at Module._extensions..js (node:internal/modules/cjs/loader:1157:10) at Object.require.extensions.<computed> [as .ts] (A:\node_modules\.pnpm\registry.npmmirror.com+ts-node@10.7.0_typescript@4.6.3\node_modules\ts-node\src\index.ts:1458:12) at Module.load (node:internal/modules/cjs/loader:981:32) { code: 'EADDRINUSE', errno: -4091, syscall: 'listen', address: '::', port: 8080 } [nodemon] app crashed - waiting for file changes before starting...
|
解决方法
- 打开终端,输入
netstat -ano
,记下端口号对应的最后一列数字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| > netstat -ano > 活动连接
> 协议 本地地址 外部地址 状态 PID > TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 1084 > TCP 0.0.0.0:443 0.0.0.0:0 LISTENING 8104 > TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4 > TCP 0.0.0.0:903 0.0.0.0:0 LISTENING 6000 > TCP 0.0.0.0:913 0.0.0.0:0 LISTENING 6000 > TCP 0.0.0.0:1025 0.0.0.0:0 LISTENING 532 > TCP 0.0.0.0:4000 0.0.0.0:0 LISTENING 16224 > TCP 0.0.0.0:5040 0.0.0.0:0 LISTENING 1140 > TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING 10616 > TCP 0.0.0.0:9197 0.0.0.0:0 LISTENING 6060 > TCP 0.0.0.0:49664 0.0.0.0:0 LISTENING 740 > TCP 0.0.0.0:49665 0.0.0.0:0 LISTENING 968 > TCP 0.0.0.0:49666 0.0.0.0:0 LISTENING 1992
|
- 输入
taskkill -PID <数字> -F
,下面命令执行则关闭8080
端口
index.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import { connect } from 'mongoose'
const mongoose = () => { connect('mongodb://localhost:27017/test', (err) => { if (err) { throw err; } else { console.log("已连接MongoDB!") } }) }
export default mongoose
|
test.ts
新建models
目录新建test.ts
文件来新建一张表
1 2 3 4 5 6 7 8 9
| import mongoose, { Model, Schema } from 'mongoose'
export const TestSchema = new Schema({ name: String, })
export const Test: Model<any> = mongoose.model('Test', TestSchema)
|
app.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import mongoose from './mongo' import { Test } from './mongo/models/test'
const port = 8080 const app = express()
mongoose()
Test.create({ name: '张三' }, (err, doc) => { if (err) { console.log(err) } else { console.log(doc) } })
|
运行成功输出如下
1 2 3 4
| pnpm start
> MongoDB连接成功! > { name: '张三', _id: new ObjectId("6271ef5df414903e3ac0c767"), __v: 0 }
|