So in my app I can connect to mongodb
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const app = require('./app');
dotenv.config({ path: './config.env' });
const DB = process.env.DATABASE.replace(
'<PASSWORD>',
process.env.DATABASE_PASSWORD
);
mongoose
// .connect(process.env.DATABASE_LOCAL, {
.connect(DB, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
})
.then(() => {
console.log('DB connection successful!');
});
const tourSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'A tour must have a name'],
unique: true,
},
rating: {
type: Number,
default: 4.5,
},
price: {
type: Number,
required: [true, 'A tour must have a price'],
},
});
const Tour = mongoose.model('Tour', tourSchema);
const testTour = new Tour({
name: 'Meteora tour',
rating: 4.9,
price: 189,
});
testTour
.save()
.then((doc) => {
console.log(doc);
})
.catch((err) => {
console.log('Error');
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`App running on port ${port}...`);
});
And as you see in the logcat the connection is successful and and a test object is stored.
App running on port 8000...
DB connection successful!
{
rating: 4.9,
_id: 61a67242927cc71a57b2a49f,
name: 'Meteora tour',
price: 189,
__v: 0
}
Here is my env file.
NODE_ENV=development
PORT=8000
USERNAME=Theo
DATABASE=mongodb+srv://Theo:<PASSWORD>@cluster0.5k97r.mongodb.net/natours?retryWrites=true&w=majority
DATABASE_LOCAL=mongodb://localhost:27107/natours
DATABASE_PASSWORD=...
Now I want to try something different. I want to run mongodb from the terminal. So I type
mongo "mongodb+srv://cluster0.5k97r.mongodb.net/natours" --username Theo
but I am getting this back
connecting to: mongodb://cluster0-shard-00-00.5k97r.mongodb.net:27017,cluster0- shard-00-01.5k97r.mongodb.net:27017,cluster0-shard-00-02.5k97r.mongodb.net:27017/natours?authSource=admin&compressors=disabled&gssapiServiceName=mongodb&replicaSet=atlas-axen7p-shard-0&ssl=true
*** It looks like this is a MongoDB Atlas cluster. Please ensure that your IP whitelist allows connections from your network.
Error: can't connect to new replica set master [cluster0-shard-00-02.5k97r.mongodb.net:27017], err: AuthenticationFailed: bad auth : Authentication failed. :
connect@src/mongo/shell/mongo.js:362:17
@(connect):2:6
exception: connect failed
exiting with code 1
How is this possible? In my app I have no problem connecting in MongoDB Atlas. I have whitelisted my IP address.
Thanks, Theo.