Junior — Middle
Is it possible to create a unified approach for performing create, read, update, and delete operations?
sobes.tech AI
Answer from AI
Yes, it is possible to create a unified approach for performing create, read, update, and delete operations — this is called CRUD (Create, Read, Update, Delete). In Node.js, the repository pattern or ORM (such as Sequelize, Mongoose) are often used, which provide a unified interface for working with data.
Here's an example of simple CRUD using Express and MongoDB (Mongoose):
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
const UserSchema = new mongoose.Schema({ name: String, age: Number });
const User = mongoose.model('User', UserSchema);
// Create
app.post('/users', async (req, res) => {
const user = new User(req.body);
await user.save();
res.status(201).send(user);
});
// Read
app.get('/users/:id', async (req, res) => {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).send('User not found');
res.send(user);
});
// Update
app.put('/users/:id', async (req, res) => {
const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (!user) return res.status(404).send('User not found');
res.send(user);
});
// Delete
app.delete('/users/:id', async (req, res) => {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) return res.status(404).send('User not found');
res.send({ message: 'User deleted' });
});
app.listen(3000);
This approach allows centralized management of all data operations, simplifying support and extension of the application.