首页 > 解决方案 > 如何通过 IP 连接到 MongoDB 数据库

问题描述

我有一个简单的问题,但找不到有效的解决方案。我有一个在 Vue 和 Mongo 上运行的应用程序。我已经使用 Mongo Atlas 进行测试,但现在是时候让应用继续生产了,所以决定使用 DigitalOcean。我用 Node.js 和 MongoDB 创建了 droplet,并设法连接了我的后端和 MongoDB。但!当我在 VPS 上运行我的文件时没有问题:

mongodb.MongoClient.connect('mongodb://localhost:27017/dbname', { useUnifiedTopology: true }, function (err, client) {
    if (err) throw err;

    app.locals.db = client.db('xxxx');
    app.listen(port, () => console.log(`Server started on port ${port}`));
})

但是,当我尝试通过本地副本上的 IP 连接时,出现超时错误。

mongodb.MongoClient.connect('mongodb://ip:27017/dbname', { useUnifiedTopology: true }, function (err, client) {
    if (err) throw err;

    app.locals.db = client.db('xxxx');
    app.listen(port, () => console.log(`Server started on port ${port}`));
})

我已经使用ip:3000(应用程序的端口)和ip:27017. 另外,我创建了一个用户并尝试使用用户并通过。一样。我尝试编辑mongod.conf并沿着 localhost 添加了 VPS 的 IP - 仍然无法正常工作。我究竟做错了什么?

标签: node.jsmongodbdigital-ocean

解决方案


You can mention the IP address in the configuration file.

You are mentioning ip:3000 parameter , rather it should be BindIP : 3000.

For more information please refer to the documentation https://docs.mongodb.com/manual/reference/configuration-options/index.html

you can also refer to a blog which I found good to solve the similar problem.

https://medium.com/@mansi.kapahi/setting-up-a-mongodb-replica-set-on-an-ec2-server-e32c4d0f0849


推荐阅读