Mongoose.connect() 没有响应



我正在学习如何在Nodejs中使用Mongodb与Mongoose。我所遵循的课程使用5.0.1版本,所以我一开始使用的是它。我用Mongodb指南针创建了一个本地数据库并将其连接起来。我的系统是Win10。VS code 1.74.2。节点18.12.1。Mongodb 4.13猫鼬5.0.1随后升级到5.13.15。我可以用旧版本的Mongoose连接数据库,但不能保存任何数据,升级新版本时连接只是超时。

我得到了"连接"在mongoose v5.0.1中使用此代码的消息

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/playground')
.then(() => console.log('Connected...'))
.catch(err => console.error('Cound not connect...', err))

然而,当我尝试使用.save()函数将json对象保存到数据库中时,它给了我错误

errmsg: 'Unsupported OP_QUERY command: insert. The client driver may require an upgrade. For more details see https://dochub.mongodb.org/core/legacy-opcode-removal',
code: 352,
codeName: 'UnsupportedOpQueryCommand'

然后我将mongoose和mongodb升级到最新版本,相同的代码给了我这个警告

(node:10772) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:10772) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

并给出错误

MongoNetworkError: failed to connect to server [localhost:27017] on first connect
所以我在代码 中添加了所需的选项
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected...'))
.catch(err => console.error('Cound not connect...', err))

它只是超时,没有任何输出。

我到处都找不到答案。任何帮助都非常感谢!SOLVED:将url改为'mongodb://127.0.0.1:27017/playground'解决了问题。

你应该给你的Mongo这样的端口:

mongoose
.connect("mongodb://localhost:27017/test")
.then(() => console.log(`x1b[32m%sx1b[0m`, "**** MONGO CONNECT 
****"))
.catch(() => console.log("eerro"))

最新更新