PASSWORD RESET

Your destination for complete Tech news

How to create a basic crud application in Node JS?

638 0
3 min read

Node.js is a popular runtime environment for building server-side applications using JavaScript. It allows developers to build scalable, high-performance applications using a non-blocking, event-driven model.

To build a CRUD application using Node.js, you can use a database driver or an Object-Relational Mapping (ORM) library to connect to the database and perform CRUD operations. You can also use a web framework, such as Express.js, to define routes and handle HTTP requests and responses.

Here is a simple example of a CRUD application in Node.js using the Express.js framework and the MongoDB database:

const express = require('express');
const app = express();

// Set up a simple in-memory store for our data
let store = {
  items: []
};

// Enable JSON parsing of request bodies
app.use(express.json());

// Create a new item
app.post('/items', (req, res) => {
  const newItem = req.body;
  store.items.push(newItem);
  res.send(newItem);
});

// Read a list of all items
app.get('/items', (req, res) => {
  res.send(store.items);
});

// Read a single item
app.get('/items/:id', (req, res) => {
  const id = req.params.id;
  const item = store.items.find(item => item.id === id);
  if (!item) {
    res.status(404).send('Item not found');
  } else {
    res.send(item);
  }
});

// Update an item
app.put('/items/:id', (req, res) => {
  const id = req.params.id;
  const item = store.items.find(item => item.id === id);
  if (!item) {
    res.status(404).send('Item not found');
  } else {
    Object.assign(item, req.body);
    res.send(item);
  }
});

// Delete an item
app.delete('/items/:id', (req, res) => {
  const id = req.params.id;
  const itemIndex = store.items.findIndex(item => item.id === id);
  if (itemIndex === -1) {
    res.status(404).send('Item not found');
  } else {
    store.items.splice(itemIndex, 1);
    res.send('Item deleted');
  }
});

// Start the server
app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

This example creates an Express.js application with a simple in-memory store for data. It defines four routes:

  • POST /items: Creates a new item
  • GET /items: Reads a list of all items
  • GET /items/:id: Reads a single item
  • PUT /items/:id:

How to connect the Node JS application with MongoDB

To add a database to the basic CRUD application in Node.js, you can use a database driver or an Object-Relational Mapping (ORM) library to connect to the database and perform CRUD operations.

Here is an example of how you can modify the previous code to use the MongoDB database and the Mongoose library:

const express = require('express');
const mongoose = require('mongoose');
const app = express();

// Connect to the MongoDB database
mongoose.connect('mongodb://localhost/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

// Create a Mongoose model for the items
const Item = mongoose.model('Item', {
  name: String,
  value: Number
});

// Enable JSON parsing of request bodies
app.use(express.json());

// Create a new item
app.post('/items', async (req, res) => {
  const newItem = new Item(req.body);
  try {
    const result = await newItem.save();
    res.send(result);
  } catch (error) {
    res.status(400).send(error);
  }
});

// Read a list of all items
app.get('/items', async (req, res) => {
  try {
    const items = await Item.find();
    res.send(items);
  } catch (error) {
    res.status(400).send(error);
  }
});

// Update an item
app.put('/items/:id', async (req, res) => {
  try {
    const item = await Item.findById(req.params.id);
    if (!item) {
      res.status(404).send('Item not found');
    } else {
      Object.assign(item, req.body);
      const result = await item.save();
      res.send(result);
    }
  } catch (error) {
    res.status(400).send(error);
  }
});

// Delete an item
app.delete('/items/:id', async (req, res) => {
  try {
    const result = await Item.deleteOne({ _id: req.params.id });
    if (result.deletedCount === 0) {
      res.status(404).send('Item not found');
    } else {
      res.send('Item deleted');
    }
  } catch (error) {
    res.status(400).send(error);
  }
});

It’s important to note that this example is a simplified version of a CRUD application, and it does not include error handling, validation, or authentication. You should consider implementing these features in a production-ready application.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.