Building a Simple CRUD API with Express and MongoDB Using Mongoose
In this blog, we'll explore how to create a basic CRUD (Create, Read, Update, Delete) API using Express.js and MongoDB with the help of Mongoose. We'll begin by setting up the project using the express-generator and then delve into the implementation of CRUD operations on a 'user' collection in MongoDB.
user.js file
const mongoose = require('mongoose');
// Connecting to MongoDB
mongoose.connect("mongodb://127.0.0.1:27017/pracMongo");
// Defining User Schema
const userSchema = mongoose.Schema({ username: String, name: String, age: Number });
// Exporting User Model
module.exports = mongoose.model("user", userSchema);
index.js file
const express = require('express');
const router = express.Router();
const userModel = require('./users');
// Create a User
router.get('/create', async function (req, res) { const user = await userModel.create({ username: "boika123", age: 21, name: "boika" });
res.send(user); });
// Retrieve All Users
router.get('/allUsers', async function (req, res) { const allUsers = await userModel.find(); res.send(allUsers); });
// Retrieve a Specific User
router.get('/one_user', async function (req, res) { const specificUser = await userModel.findOne({ username: "boika123" }); res.send(specificUser); });
// Delete a User
router.get('/delete', async function (req, res) { const deletedUser = await userModel.findOneAndDelete({ username: "boika123" }); res.send(deletedUser); });
// Update a User
i have kept it as Home-Work for you , try doing it yourself and once done and comment it
// Exporting the Router
module.exports = router;
By following this guide, you've set up a basic Express.js server with MongoDB integration using Mongoose. This code provides a foundation for building more complex applications with additional features and routes. Feel free to expand upon this base to create a more comprehensive API tailored to your specific needs.