Skip to content

Instantly share code, notes, and snippets.

@kavicastelo
Created April 23, 2025 17:52
Show Gist options
  • Select an option

  • Save kavicastelo/4ccbb711ad7d290e0438fe6475ca129a to your computer and use it in GitHub Desktop.

Select an option

Save kavicastelo/4ccbb711ad7d290e0438fe6475ca129a to your computer and use it in GitHub Desktop.
MongoDB Learning Module 3 (Interns) – MongoDB with Node.js
const connect = require("../db/mongoClient");
(async () => {
const { client, db } = await connect();
const employees = db.collection("employees");
await employees.deleteOne({ name: "Bob" });
console.log("❌ Bob deleted");
await client.close();
})();
const connect = require("../db/mongoClient");
(async () => {
const { client, db } = await connect();
const employees = db.collection("employees");
const results = await employees.find({ department: "Engineering" }).toArray();
console.log("🔍 Found:", results);
await client.close();
})();
const connect = require("../db/mongoClient");
(async () => {
const { client, db } = await connect();
const employees = db.collection("employees");
await employees.insertMany([
{ name: "Alice", age: 25, department: "HR", skills: ["People", "Communication"] },
{ name: "Bob", age: 30, department: "Engineering", skills: ["JavaScript", "Node.js"] },
]);
console.log("📥 Employees inserted");
await client.close();
})();
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017"; // or your Atlas URI
const client = new MongoClient(uri);
const dbName = "companyDB";
async function connect() {
await client.connect();
console.log("✅ Connected to MongoDB");
const db = client.db(dbName);
return { client, db };
}
module.exports = connect;
node-mongodb-module/
├── db/
│   └── mongoClient.js
├── scripts/
│   ├── insert.js
│   ├── find.js
│   ├── update.js
│   └── delete.js
├── package.json
└── README.md
const connect = require("../db/mongoClient");
(async () => {
const { client, db } = await connect();
const employees = db.collection("employees");
await employees.updateOne({ name: "Alice" }, { $set: { age: 26 } });
console.log("🔁 Alice updated");
await client.close();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment