mongodb使用
(1)下载mongodb,下载地址:downloads.mongodb.com
要创建一个文件夹data,在data下面创建文件夹db,位置放mongodb下哪都可以,数据是存在这里的,但mongodb不会自动创建
(2)连接mongodb数据库
1.安装连接要用的驱动:npm i mongoose
2.启动mongodb:net start mongodb (注:每次连接之前记得要启动,在bin路径下以管理员身份启动)
3.写连接数据库语句,
4.写模型
(3)解决跨域
1.执行npm i cors
2.app.use(require(‘cors’)())
(4)解析json数据
1.app.use(express.json())
(5)nodemon index.js可以自动重启服务
1.安装nodemon :npm install -g nodemon
(6)笔记本会禁止运行脚本,解决办法:
1.管理员身份打开PowerShell
2.输入set-ExecutionPolicy RemoteSigned,选择y或a
问题解决:
(1)连接数据失败,原因是没启动数据库
(node:5468) UnhandledPromiseRejectionWarning: MongoTimeoutError: Server selection timed out after 30000 ms
at Timeout.setTimeout [as _onTimeout] (C:\Users\deng\Desktop\my-element-admin\element-admin\node_modules\mongodb\lib\core\sdam\server_selection.js:308:9)
at listOnTimeout (timers.js:324:15)
at processTimers (timers.js:268:5)
(node:5468) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5468) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated.
In the future, promise rejections that are not handled will terminate the Node.js process wit
(2)警告{ useUnifiedTopology: true },在mongoose.connect第二个参数里添加下面代码可解决
useNewUrlParser: true, useUnifiedTopology: true
userCreateIndex:true
(3)post插入数据只有一条字段
原因:字段要在模型里定义了才能插入字段对应的数据,忘记定义了
(4)`很容易写成’,导致不能动态传值
(5)html改动态图片src前面要加:
(6)删掉集合
User.db.dropColletion(‘User’)
(7)注册时用户名字段唯一
unique:true
(8)密码加密
安装依赖:npm i bcrypt
在模型字段里
password:{
type: String,
set(val){
return require(‘bcrypt’).hashSync(val.10)
}
}
10表示安全级别,越高速度越慢
express使用
(1)安装node v11.5.0版本,带的npm版本是6.4.1 有时候需要升级为8.0以上
(2)express使用
1.全局安装npm install express -g
2.查看版本号npm list express
1.初始化npm init(生成package.json用的)一路回车
2.安装npm install express --save (生成node_modules和package-lock.json用的)
npm install express @next表示下一个版本5,还没出
————————————————
版权声明:本文为CSDN博主「qq_43919485」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_43919485/article/details/104388792