Files
broccolini-bot/scripts/test-mongodb.js

46 lines
1.2 KiB
JavaScript

/**
* Test MongoDB connection using the native driver.
* Uses MONGODB_URI from .env (or ENV_FILE when set). Run: npm run test-mongodb
*/
const path = require('path');
const dotenv = require('dotenv');
const envPath = process.env.ENV_FILE ? path.resolve(process.cwd(), process.env.ENV_FILE) : undefined;
dotenv.config({ path: envPath });
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = (process.env.MONGODB_URI || '').trim();
const scheme = uri.split('://')[0];
if (!uri) {
console.error('MONGODB_URI is not set in .env');
process.exit(1);
}
if (scheme !== 'mongodb' && scheme !== 'mongodb+srv') {
console.error('MONGODB_URI must start with mongodb:// or mongodb+srv://');
process.exit(1);
}
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});
async function run() {
try {
await client.connect();
await client.db('admin').command({ ping: 1 });
console.log('Pinged your deployment. You successfully connected to MongoDB!');
} finally {
await client.close();
}
}
run().catch((err) => {
console.error(err);
process.exit(1);
});