CRUD (Create, Read, Update, Delete) API with Nodejs example
To create a basic CRUD (Create, Read, Update, Delete) API with Node.js, you will need to use a web framework such as Express. Here's an example of how you can set up a basic CRUD API with Node.js and Express:
Install the required packages:
npm install express body-parser mongoose
Set up the database connection:
const mongoose = require('mongoose');
// Replace "YOUR_MONGO_URI" with your actual MongoDB connection URI
mongoose.connect('YOUR_MONGO_URI', { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('Connected to MongoDB');
});
Define the schema for your data:
const Schema = mongoose.Schema;
const TaskSchema = new Schema({
title: String,
description: String,
completed: Boolean
});
const Task = mongoose.model('Task', TaskSchema);
Create the routes for the API:
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
router.use(bodyParser.json());
// Create a new task
router.post('/tasks', function(req, res) {
const task = new Task(req.body);
task.save(function(err, task) {
if (err) return res.status(500).send(err);
res.status(201).send(task);
});
});
// Get a list of all tasks
router.get('/tasks', function(req, res) {
Task.find({}, function(err, tasks) {
if (err) return res.status(500).send(err);
res.send(tasks);
});
});
// Get a single task by id
router.get('/tasks/:id', function(req, res) {
Task.findById(req.params.id, function(err, task) {
if (err) return res.status(500).send(err);
if (!task) return res.status(404).send();
res.send(task);
});
});
// Update a task by id
router.put('/tasks/:id', function(req, res) {
Task.findByIdAndUpdate(req.params.id, req.body, { new: true }, function(err, task) {
if (err) return res.status(500).send(err);
if (!task) return res.status(404).send();
res.send(task);
});
});
// Delete a task by id
router.delete('/tasks/:id', function(req, res) {
Task.findByIdAndRemove(req.params.id, function(err, task) {
if (err) return res.status(500).send(err);
That's a simple example you can try. Comment if any doubt.