← Back to Node.js Course | Chapter 9: Database Integration | Lesson 7 of 7

CRUD operations

CRUD stands for create, read, update, delete: the four things every app does with stored data.

In this page:

  1. CRUD operations

CRUD operations

Wrap CRUD in a small data layer so routes stay simple. Whatever the database, the operations are the same ideas: insert a record, query records, change a record and remove one. Return meaningful results and handle not-found cases.

Note: Keep database code in one module so you can swap the database later.

Example: CRUD operations

javascript
class Store {
  constructor() { this.rows = new Map(); this.next = 1; }
  create(data) { const row = { id: this.next++, ...data }; this.rows.set(row.id, row); return row; }
  read(id) { return this.rows.get(id) || null; }
  update(id, patch) { const r = this.read(id); if (!r) return null; Object.assign(r, patch); return r; }
  remove(id) { return this.rows.delete(id); }
}
const s = new Store();
const u = s.create({ name: "Ada" });
console.log(s.read(u.id));
console.log(s.update(u.id, { name: "Ada L." }));
console.log(s.remove(u.id), s.read(u.id));

// Output:
// { id: 1, name: 'Ada' }
// { id: 1, name: 'Ada L.' }
// true null

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Scattering queries across route handlers
  2. Not handling missing records
  3. Forgetting to validate input
Chapter Summary
  • Create, read, update, delete
  • Keep data access in one layer
  • Handle not found
  • Validate input
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.