DEV Community

Nilesh Raut
Nilesh Raut

Posted on • Updated on

Build a CRUD Rest API in JavaScript using Nodejs in 5 min

First, we'll need to set up our project and install the necessary packages. We'll be using Express, a popular Nodejs framework for building web applications, and Mongoose, a package for interacting with MongoDB databases.

Create a new directory for your project and navigate into it:

mkdir my-api
cd my-api

Initialize a new Nodejs project with NPM:

npm init
Install Express and Mongoose:

npm install express mongoose
Now we're ready to start building our API!

Create a new file called server.js and add the following code:
javascript

const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = 3000;
// Connect to MongoDB
mongoose.connect('mongodb://localhost/my-api', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.error(error);
});
const schema = new mongoose.Schema({
name: String,
age: Number,
});
// Create a model from the schema
const User = mongoose.model('User', schema);
// Set up routes for our API
app.get('/users', async (req, res) => {
const users = await User.find();
res.send(users);
});
app.post('/users', async (req, res) => {
const user = new User(req.body);
await user.save();
res.send(user);
});
app.put('/users/:id', async (req, res) => {
const { id } = req.params;
const user = await User.findByIdAndUpdate(id, req.body, { new: true });
res.send(user);
});
app.delete('/users/:id', async (req, res) => {
const { id } = req.params;
await User.findByIdAndDelete(id);
res.sendStatus(204);
});
// Start the server
app.listen(port, () => {
console.log(
Server started on port ${port});
});
`
Let's go through this code step by step:

  • We import the necessary packages, set up our Express app, and define a port to listen on.
  • We connect to our MongoDB database using the Mongoose package. Replace the mongodb://localhost/my-api URL with the URL of your own database if you're using a different one.

If you are looking for a great tech blog that offers insightful content on the latest technology trends and gadgets, be sure to check out CLICK HERE. With its in-depth articles and helpful tips, this blog is a valuable resource for anyone interested in staying up-to-date on the latest advancements in the tech world. And if you're looking to boost your own website's visibility, be sure to include a do-follow

Top comments (0)