Image

Express.js getting start with MongoDB

Express.js is a great way to build web applications and APIs using Node.js.

Prerequisites:

Before you start with Express.js, make sure you have Node.js and npm (Node Package Manager) installed on your system. You can download and install them from the official website: Node.js.

Create a Project Directory:

Create a directory for your Express.js project, and navigate to that directory using your terminal or command prompt.

mkdir my-express-app
cd my-express-app

Initialize a Node.js Project:

Initialize a new Node.js project by running npm init. You will be prompted to enter some information about your project. You can just press Enter to accept the default values for most of the prompts.

npm init

Install Express: Use npm to install the Express.js package in your project directory.

npm install express --save

Create an Express Application:

Create an entry point for your Express application, typically named app.js or server.js. In this file, require Express and create an Express application:

const express = require('express');
const app = express();
const port = 3000; // You can change the port as needed

app.get('/', (req, res) => {
  res.send('Hello, Express.js!');
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Start the Express Application:

Run your Express application using the following command:

node app.js

Your Express app should now be running, and you can access it by opening a web browser and going to http://localhost:3000 (or the port you specified in your code).

npm init -y
npm i express
const express = require("express");
const app = express();

app.get("/api/people", function(req, res) {
    const data = [
        { name: "Bobo", age: 22 },
        { name: "Nini", age: 23 },
    ];
    return res.status(200).json(data);
});

app.listen(8000, function() {
    console.log("Server running at port 8000...");
});

Response Header

res.set({
    "Location": "http://domain/api/users/3",
    "X-Rate-Limit-Limit": 60,
});

Or

res.append("X-Rate-Limit-Remaining": 58);

Dynamic URL

app.get("/api/people/:id", function(req, res) {
    const id = req.params.id;

    return res.status(200).json({ id });
});

Routes

routes.js

const express = require("express");
const router = express.Router();

router.get("/people", function(req, res) {
    const people = [
        { name: "Bobo", age: 22 },
        { name: "Nini", age: 23 },
    ];
    return res.status(200).json(people);
});

router.get("/people/:id", function(req, res) {
    const id = req.params.id;
    return res.status(200).json({ id });
});

module.exports = router;

index.js

const express = require("express");
const app = express();
const routes = require("./routes");

app.use("/api", routes);
app.listen(8000, function() {
    console.log("Server running at port 8000...");
});

MongoDB

npm i mongodb body-parser
const express = require("express");
const app = express();

const { MongoClient, ObjectId } = require("mongodb");
const mongo = new MongoClient("mongodb://localhost");
const db = mongo.db("travel");

const bodyParser= require("body-parser");

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get("/api/records", async function (req, res) {
    try {
        const result = await db
                            .collection("records")
                            .find()
                            .toArray();
        res.json({
            meta: { total: result.length },
            data: result
        });
    } catch {
        res.sendStatus(500);
    }
});

app.get("/test", function(req, res) {
    return res.json(req.query);
});
localhost:8000/test?sort[name]=1&filter[from]=Yangon&filter[to]=Yangon&page=2
app.get("/api/records", async function (req, res) {
    const options = req.query;

    // validate options, send 400 on error
    const sort = options.sort || {};
    const filter = options.filter || {};
    const limit = 10;
    const page = parseInt(options.page) || 1;
    const skip = (page - 1) * limit;

    for (i in sort) {
        sort[i] = parseInt(sort[i]);
    }

    try {
        const result = await db
                                .collection("records")
                                .find(filter)
                                .sort(sort)
                                .skip(skip)
                                .limit(limit)
                                .toArray();
        /*
        res.json({
            meta: { total: result.length },
            data: result,
        });
        */

        res.json({
            meta: {
                skip,
                limit,
                sort,
                filter,
                page,
                total: result.length,
            },
            data: result,
            links: {
                self: req.originalUrl,
            }
        });

    } catch {
        res.sendStatus(500);
    }
});
localhost:8000/api/records?filter[to]=Yangon&sort[name]=1&page=1 

Express validation

npm i express-validator
const {
    body,
    param,
    validationResult
} = require("express-validator");
app.post(
    "/api/records",
    [
        body("name").not().isEmpty(),
        body("from").not().isEmpty(),
        body("to").not().isEmpty(),
    ],
    async function (req, res) {
        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.status(400).json({
                errors: errors.array()
            });
        }
        try {
            const result = await db
                            .collection("records")
                            .insertOne(req.body);

            const _id = result.insertedId;

            res.append("Location", "/api/records/" + _id);

            res.status(201).json({
                meta: { _id },
                data: result,
            });
        } catch {
            res.sendStatus(500);
        }
    }, 
);
app.put("/api/records/:id", async function (req, res) {
    try {
        const _id = new ObjectId(req.params.id);
        const result = await db
                        .collection("records")
                        .findOneAndReplace(
                            { _id },
                            req.body,
                            { returnDocument: "after"
                        });

        res.json({
            meta: { _id },
            data: result.value,
        });

    } catch {
        res.sendStatus(500);
    }
});

PUT

app.patch("/api/records/:id", async function (req, res) {
    try {
        const _id = new ObjectId(req.params.id);
        const result = await db
                        .collection("records")
                        .findOneAndUpdate(
                            { _id },
                            { $set: req.body },
                            { returnDocument: "after" },
                        );

        res.json({
            meta: { _id },
            data: result.value,
        });
    } catch {
        res.sendStatus(500);
    }
});

DELETE

app.delete("/api/records/:id", async function (req, res) {
    try {
        const _id = new ObjectId(req.params.id);
        await db.collection("records").deleteOne({ _id });
        res.sendStatus(204);
    } catch {
        res.sendStatus(500);
    }
});

aung thu oo

#HIRE ME

OPEN TO WORK

Ko Aung Thu Oo

Having over 15 years of working experience in Laravel, PHP, Flutter, Node.Js, Vue.JS, JAVA. Strong information technology professional with a degree i...

View detail