Javascript 如何通过express和mongoose连接到本地网络中的MongoDB
我正在用express和mongoose设置一个服务器,我希望它能在本地网络中的其他机器上使用。bind_ip变量已在Mongodb配置文件中设置为0.0.0.0Javascript 如何通过express和mongoose连接到本地网络中的MongoDB,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,我正在用express和mongoose设置一个服务器,我希望它能在本地网络中的其他机器上使用。bind_ip变量已在Mongodb配置文件中设置为0.0.0.0 const connection = mongoose .connect( "mongodb://192.168.254.104/db", { useNewUrlParser: true } ) .then(() => console
const connection = mongoose
.connect(
"mongodb://192.168.254.104/db",
{
useNewUrlParser: true
}
)
.then(() => console.log("Connected to MongoDB"))
.catch(error => console.log(error));
我已尝试在手机上连接,但服务器响应显示找不到数据库。这是mongodb连接字符串的格式:
mongodb://[username:password@]host1[:port1][,...hostN[:portN]]][/[database][?options]]
如果要连接到localhost数据库,则字符串如下所示:
"mongodb://localhost:27017/mydb"
其中“mydb”是本地计算机上的数据库名称。请尝试以下方法:
mongoose.Promise = Promise;
mongoose.set('useCreateIndex', true);
var mongooseOptions = { useNewUrlParser: true }
mongoose.connect('mongodb://localhost:27017/MyDatabase', mongooseOptions, function(err) {
if (err) {
console.error('System could not connect to mongo server.')
console.log(err)
} else {
console.log('System connected to mongo server.')
}
});
首先,您应该在本地服务器上运行MongoDB服务器 默认运行端口为:27017
mongoose.connect('mongodb://localhost:27017/', {
dbName: 'event_db',
useNewUrlParser: true,
useUnifiedTopology: true
}, err => err ? console.log(err) : console.log('Connected to database'));
或者你可以
mongoose.connect('mongodb://localhost:27017/event_db');
您缺少端口号,最好在大多数情况下使用localhost,我想您是否要将mongodb服务器公开到您的LAN?因为您显示的代码是服务器端代码。这是否意味着您要运行多个express服务器?我只希望它们使用相同的express服务器和数据库。对,在这种情况下,无需将mongodb服务器公开到您的LAN。您的express服务器已经可以从LAN中的所有计算机访问,并且只有express服务器需要访问mongodb服务器。由于两者在同一台机器上,因此根本不需要任何特殊的配置。您好,如果您的问题得到解决,您应该接受答案并帮助社区。您在本例中提供的连接URL在本例中是错误的,因为他正试图连接到本地网络192.168.X.X。连接URL,在本例中,您提供的是错误的,因为他正在尝试连接到本地网络192.168.X.X。