前言
本文主要使用egg框架和mongodb数据库,简单实现增删改查接口。具体包括如下:
- 链接数据库
- 创建数据表
- 添加数据
- 查找数据
- 修改数据
- 删除数据
搭建项目
$ mkdir egg-example && cd egg-example
$ npm init egg --type=simple
$ npm i
启动项目
npm run dev
或者
npm run start
在浏览器的地址栏中输入http://localhost:7001/
页面会显示 hello egg
说明项目构建成功
链接数据库
首先下载egg-mongoose
npm i egg-mongoose --save
配置config/plugin.js
'use strict';
module.exports = {
mongoose:{
enable:true,
package:"egg-mongoose"
}
};
在config/config.default.js
'use strict';
module.exports = appInfo => {
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1641975352438_173';
// add your middleware config here
config.middleware = [];
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
//mongoose数据库配置
config.mongoose={
url:'mongodb://127.0.0.1:27021/VietNamVisa',//端口号27021数据库名VietNamVisa
options:{useNewUrlParser:true,useUnifiedTopology:true},//其他配置警告解除方法
}
return {
...config,
...userConfig,
};
};
开启数据库
打开电脑上的mongodb文件夹下的bin目录cmd
执行mongod --dbpath=存储数据的路径 --port=数据库的端口号
例如
mongod --dbpath=E:\myNode\VietNamVisa\init\app\db --port=27021
显示一坨代码结尾例类似这样
s":{"type":"Windows_NT","name":"win32","architecture":"x64","version":"10.0.19041"},"platform":"'Node.js v16.13.1, LE (unified)","version":"3.7.3|5.13.14"}}}
说明启动成功