简体   繁体   中英

How to connect to MongoDB in local network with express and mongoose

I'm setting up a server with express and mongoose and I'd like it to be usable in other machines present in my local network. The bind_ip variable has already been set to 0.0.0.0 in the Mongodb configuration file.

const connection = mongoose
    .connect(
        "mongodb://192.168.254.104/db",
        {
            useNewUrlParser: true
        }
    )
    .then(() => console.log("Connected to MongoDB"))
    .catch(error => console.log(error));

I've tried connecting on my mobile phone but the server response says it didn't find the database.

First, you should run a MongoDB server on Local.

Default running port is: 27017

mongoose.connect('mongodb://localhost:27017/', {
    dbName: 'event_db',
    useNewUrlParser: true,
    useUnifiedTopology: true 
}, err => err ? console.log(err) : console.log('Connected to database'));

Or you can do

mongoose.connect('mongodb://localhost:27017/event_db');

This is the format of mongodb connection String:

mongodb://[username:password@]host1[:port1][,...hostN[:portN]]][/[database][?options]]

If you want to connect to a localhost database then the string would be like this:

"mongodb://localhost:27017/mydb"

Where "mydb" is the DB name on your local machine.

try this way :

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.')
    }
});

Your code is fine. you should double check if "db" exist. if it is, try to connect to mongo via ssh and see if the settings are correct on the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM