起因
使用mongoose官方文档的connect连Mongodb cloud免费数据库,始终连不上
await mongoose.connect('mongodb://127.0.0.1:27017/test');
就一句代码,一个api,一个url多简单。死活连不上,困扰了我好久。
原本一开始我没有用mongoose,直接用的mongodb官方库创建连接没问题,还能增删改查
const client = new MongoClient(url)
同样一个api,一个url,就能连上Mongodb数据库。
分析
Mongodb cloud免费数据库url一般是:
mongodb+srv://test:<db_password>@notes.wwwdz.mongodb.net/?retryWrites=true&w=majority&appName=notes
而mongoose 给的示例代码里面的url是 mongodb://127.0.0.1:27017/test
很明显前者多了个 +srv, 同时后者通过/test 来制定数据库名称。但是Mongodb Cloud的免费数据库url是通过?&appName=notes 参数的形式指定!!!
解决
认真查看了mongoose官方文档找到了 mongoose.connect() 这个api的文档!
他有两个参数:
- 第一个是url,也就是数据库地址
- 第二个是options,一个对象
贴一下原话:
···
The connect method also accepts an options object which will be passed on to the