If you want to test your connection string, you can use the following code:
const mongoose = require('mongoose');
mongoose.set('strictQuery', true);
async function testConnection() {
try {
await mongoose.connect(`YOUR_URI_HERE`, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('Connected to MongoDB successfully!');
process.exit(0);
} catch (error) {
console.error('Error connecting to MongoDB:', error);
process.exit(1);
}
}
testConnection();
Install Node.js (if you haven't already):
Mac: Download from nodejs.org or use brew install node
Windows: Download from nodejs.org or use choco install nodejs
Install mongoose:
npm install mongoose
Save the code as test-connection.js and replace YOUR_URI_HERE with your actual MongoDB connection string
Run it:
Mac: node test-connection.js
Windows: node test-connection.js
If it doesn't work (shows "Error connecting to MongoDB" or similar), re-follow the steps from the previous lesson to ensure you have a valid connection string.