import { MongoClient } from 'mongodb'; import { randomBytes } from 'node:crypto'; const uri = process.env.BHYLU_MONGO_URI; let endpoint; try { endpoint = new URL(uri); } catch { throw new Error('Use the dedicated loopback MongoDB lab'); } if ( process.env.BHYLU_NODE_DB_LAB !== 'YES' || endpoint.protocol !== 'mongodb:' || endpoint.hostname !== '127.0.0.1' || !endpoint.port || endpoint.port === '27017' ) throw new Error('Use the dedicated loopback MongoDB lab'); const client = new MongoClient(uri, { serverSelectionTimeoutMS: 5000 }); await client.connect(); const database = client.db('bhylu_node_' + randomBytes(8).toString('hex')); try { const kits = database.collection('kits'); await kits.insertMany([ { _id: 701, name: 'tripod', available: 3 }, { _id: 702, name: 'binoculars', available: 2 }, { _id: 703, name: 'torch', available: 0 }, ]); const names = (await database.listCollections({}, { nameOnly: true }).toArray()) .map((row) => row.name) .sort(); console.log(names.join(',')); console.log(await kits.countDocuments({})); } finally { try { await database.dropDatabase(); } finally { await client.close(); } }