CRUD Operations with Node.js and MongoDB
Now that you know how to connect to MongoDB from Node.js, it's time to perform CRUD operations! We'll use the MongoDB driver to insert, find, update, and delete documents – all from within our Node.js application.
Setup: Getting the Collection
First, let's create a function to get our collection (reusing the connection):
require('dotenv').config();const { MongoClient } = require('mongodb');
const url = process.env.MONGODB_URI;const dbName = process.env.DB_NAME;
let db = null;
async function getCollection(collectionName) { if (!db) { const client = new MongoClient(url); await client.connect(); db = client.db(dbName); } return db.collection(collectionName);}Think of CRUD operations as the basic actions you can do with any data: Create new records, Read existing records, Update records, and Delete records.
CREATE: Inserting Documents
Insert One Document
async function createUser(userData) { try { const collection = await getCollection('users'); const result = await collection.insertOne(userData); console.log('User created with ID:', result.insertedId); return result.insertedId; } catch (err) { console.error('Error creating user:', err); }}
<!-- Usage -->createUser({ name: 'Alice', email: 'alice@example.com', age: 28});Insert Multiple Documents
async function createMultipleUsers(users) { try { const collection = await getCollection('users'); const result = await collection.insertMany(users); console.log('Inserted count:', result.insertedCount); console.log('Inserted IDs:', result.insertedIds); } catch (err) { console.error(err); }}READ: Finding Documents
Find All Documents
async function findAllUsers() { try { const collection = await getCollection('users'); const users = await collection.find({}).toArray(); console.log('All users:', users); return users; } catch (err) { console.error(err); }}Find with Filter
async function findUsersByAge(minAge) { try { const collection = await getCollection('users'); const users = await collection .find({ age: { $gt: minAge } }) .toArray(); console.log(`Users older than ${minAge}:`, users); return users; } catch (err) { console.error(err); }}Find One Document
async function findUserByEmail(email) { try { const collection = await getCollection('users'); const user = await collection.findOne({ email }); if (user) { console.log('User found:', user); } else { console.log('User not found'); } return user; } catch (err) { console.error(err); }}UPDATE: Modifying Documents
Update One Document
async function updateUserAge(email, newAge) { try { const collection = await getCollection('users'); const result = await collection.updateOne( { email }, { $set: { age: newAge } } ); if (result.matchedCount === 0) { console.log('No user found with that email'); } else { console.log('User updated'); } } catch (err) { console.error(err); }}Update Multiple Documents
async function markAllActive() { try { const collection = await getCollection('users'); const result = await collection.updateMany( {}, { $set: { active: true } } ); console.log('Updated', result.modifiedCount, 'users'); } catch (err) { console.error(err); }}DELETE: Removing Documents
Delete One Document
async function deleteUser(email) { try { const collection = await getCollection('users'); const result = await collection.deleteOne({ email }); if (result.deletedCount === 0) { console.log('User not found'); } else { console.log('User deleted'); } } catch (err) { console.error(err); }}Delete Multiple Documents
async function deleteInactiveUsers() { try { const collection = await getCollection('users'); const result = await collection.deleteMany({ active: false }); console.log('Deleted', result.deletedCount, 'users'); } catch (err) { console.error(err); }}Two Minute Drill
- CRUD operations in Node.js use the same methods as the MongoDB shell.
- Always use `await` with database operations – they're asynchronous.
- `insertOne()` and `insertMany()` return objects with `insertedId`/`insertedIds`.
- `find()` returns a cursor – use `toArray()` to get all results.
- Update operations return `matchedCount` and `modifiedCount`.
- Delete operations return `deletedCount`.
- Always wrap database operations in try/catch for error handling.
Need more clarification?
Drop us an email at career@quipoinfotech.com
