NodeJS and MongoDB CRUD operations using Mongoose js library

If you are developing API or pages in NodeJS and Using the database MongoDb as storage, here is the example which gives you a getting started code to manage data in MongoDB database from NodeJs code. We will use MongooseJS library, which will work as a Database Layer to communicate with MongoDb. This library has all the required functionality for developing Production-ready applications. We are using ExpressJS to create the routes and to create server-side requests handler. 

Here, we are taking the example of books API where we want to create the CRUD operations.

Here is the schema for book entity:

const mongoose=require("mongoose");

const book=mongoose.Schema({
    title:{
        type:String,
        require:true
    },
    author:{
        type:String,
        require:true

    },
    pages:{
        type:Number,
        require:true

    },
    active:Boolean

});
module.exports=mongoose.model("books",book);

And using the above book schema, we can define the CRUD operations easily.

const ex = require("express");
const {route} = require("express/lib/application");
const book = require("../model/book");
const router = ex.Router();


//get all the books

router.get("/", async (req, resp) => {
    try {
        const books = await book.find()
        resp.json(books);

    } catch (err) {
        resp.json(err);

    }
});
//get single book

router.get("/:bookId", async (req, resp) => {
    const bookId = req.params.bookId;
    try {
        const c = await book.findById(bookId);
        resp.json(c);
    } catch (error) {
        resp.json(error);


    }

});


//create book

router.post("/", async (req, resp) => {
    const bookPost = await book.create(req.body);
    console.log("book details return" + bookPost);
    resp.json(bookPost);

});

//delete book

router.delete("/:bookId", async (req, resp) => {
    try {
        console.log("book id--" + req.params.bookId);
        await book.deleteOne({
            "_id": req.params.bookId
        });
        resp.status(200).json({
            message: "done",
        });
    } catch (error) {
        resp.json(error);
    }
});


//update book
router.put("/:bookId", async (req, resp) => {
    const bookId = req.params.bookId;
    console.log("bookId  " + bookId);
    try {

        const c= await book.updateOne(
            {
                "_id": bookId
            },
            req.body
        )
        console.log("book details" + c);
        resp.json(c)
    } catch (error) {
        resp.json(error);
    }


});

module.exports = router;

In .env file you can. declare the PORT and Database connection String.

PORT=2000
DB_CONNECTION_URL=mongodb://localhost:27017/test

After running the above APIs, you can see the data in the database.

And final index.js from where everything would start.

const mongoose=require("mongoose");
const express=require("express");
const booksRouter=require("./routes/books");
const app=express();
const bodyParser=require("body-parser");
app.use(bodyParser.json());

app.use("/api/v1/books",booksRouter);


require("dotenv").config()

mongoose.connect(process.env.DB_CONNECTION_URL);

app.listen(process.env.PORT, ()=>{
    console.log("server is running");

});

 

Tags