CRUD operations
CRUD stands for create, read, update, delete: the four things every app does with stored data.
In this page:
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
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
- Scattering queries across route handlers
- Not handling missing records
- 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: