bhylu.com

Advertisements

Node.js MongoDB Connection

The MongoDB driver talks to a running database service. A collection API is not an in-memory JavaScript array, and a mocked array is not evidence of a real database operation.

How it works

The reviewed Node driver is mongodb 6.17.0 against a private MongoDB Community 8.0.12 process. Each example requires an explicit loopback lab URI and creates a randomly named owned database. MongoDB commonly materializes databases and collections when data is first written; the seed insert is the deliberate creation step here. Finally removes only that generated database and closes the client. No Atlas account or existing application collection is used.

Run the code

Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as mongo-lab.mjs in a separate empty exercises folder and run node mongo-lab.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs. In that separate project, install the reviewed packages with npm install --save-exact mongodb@6.17.0. These are teaching dependencies, not changes to the Bhylu website package tree. This database example is reviewed on Node 22.15.1 against its named real database lab. Do not run it against an existing application database. Read the dedicated lab requirements below before execution.

Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.

Dedicated MongoDB lab

Use MongoDB Community 8.0.12 and mongodb driver 6.17.0 in a disposable authenticated loopback instance. The script requires BHYLU_NODE_DB_LAB=YES and BHYLU_MONGO_URI, including the lab host, port, authentication database and your private generated credentials. It creates a random bhylu_node_ database, inserts fictional records and drops only that database in finally. Do not use an Atlas or existing application URI. The review is a standalone instance, not a replica-set transaction, sharding or failover test.

Example

mongo-lab.mjs

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();
  }
}

Expected result

kits
3

The actual server contains the intended collection and three original fictional kit documents. Connection credentials stay in the review environment rather than entering downloaded source or visible output. The URI guard is an accident-prevention measure, not a sandbox for malicious source.

Use the Node.js API reference for the precise version contract.

Advertisements