Reputation: 3543
trying to access to an external database in local via my server, I executed this code server side:
console.log('MONGODB_URI_LOCAL::', config.MONGODB_URI_LOCAL)
const mongooseLocal = require('mongoose');
const connectionOptions = { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false };
const conn = mongooseLocal.createConnection(config.MONGODB_URI_LOCAL, connectionOptions);
conn.on("error", console.error.bind(console, "connection error: "));
conn.once("open", async () => {
console.log("Connected successfully");
});
And I get this error:
MongoError: Authentication failed
here is the format of the URI:
config.MONGODB_URI_LOCAL = mongodb://user_name:my_password@localhost:27017/my_db_name
This is the first time I try to connect to a local database so:
Is this possible to connect to a local database from server and read or write data ?
If yes How can I fix this issue ?
Upvotes: 0
Views: 93
Reputation: 63
Here's an approach that you can use. This approach enables you to export your connection logic to other parts of your code.
const mongoose = require('mongoose')
const connect = async (callback) => {
try{
const connectionOptions = {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
};
await mongoose.connect(config.MONGODB_URI_LOCAL, connectionOptions)
// On successful connection you can call your callback function
callback()
}catch(err){
console.log(err)
process.exit(1)
}
}
connect()
Upvotes: 1