Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mfrancois3k/c212b6cbe64291f3a4b85df76f8a7324 to your computer and use it in GitHub Desktop.
Save mfrancois3k/c212b6cbe64291f3a4b85df76f8a7324 to your computer and use it in GitHub Desktop.
MongoDB_integration-to-web-app_reference.md

MongoDB Integration to Web App - Reference

This gist was created by using a reference article by Roopali Singh in Medium.com.

Installation

npm install mongoose

Create userModel.js with userSchema for database structure

// userModel.js
import mongoose from "mongoose";

const userSchema = new mongoose.Schema(
  {
    
    // It atomatically assigns a unique _id, so we don't need to define another id for it.
    
    firstName: { type: String, required: true },
    lastName: { type: String, required: false },
    email: { type: String, required: true, unique: true },
    pin: { type: Number, required: true },
  },
  {
    timestamps: true,
    // Timestamp of creating a record and last update of record.
  }
);

Create mongoose model to call on userSchema:

const User = mongoose.model("User", userSchema);

export default User;

Create userRouter.js file to set API routes for CRUD operations

import express from "express";
import User from "./userModel.js ";

// express.Router() =>  a function to make code Modular, instead of
// creating all routes in server.js we can define multiple files
// to have our routers...

const userRouter = express.Router();

// nature of mongoose operation is async
// so we will define the async functions here.

export default userRouter;

Connect mongoose to database with server.js file

// server.js file will connect userRouter.js to database

import express from "express";
import mongoose from "mongoose";

mongoose.connect(process.env.MONGODB_URL ||
"mongodb://localhost/your_app_name", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
});

Import userRouter into server.js to connect server.js to userRouter.js

import userRouter from "./userRouter.js";

app.use("/api/users", userRouter);

Now, server.js looks like this:

import express from "express";
import dotenv from "dotenv"; // npm install dotenv
import mongoose from "mongoose";
import userRouter from "./router/userRouter.js";

dotenv.config(); // to use .env file content

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));


// To connect mongoose to mongoDB database

mongoose.connect(process.env.MONGODB_URL ||
"mongodb://localhost/your_app_name", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
});


// To connect server.js to userRouter.js

app.use("/api/users", userRouter);


// listen command

const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`Serve at http://localhost:${port}`);
});

Return to userRouter.js file to create routes for CRUD operations:

// userRouter.js
import express from "express";
import User from "./userModel.js ";

const userRouter = express.Router();

// 1) to read/fetch all users:

userRouter.get(
  "/seed",async (request, response) => {

    // there is no condition defined in find, so it will
    // fetch all users.
    const allUsers = await User.find({});

    response.send({ allUsers });
  };
);


// 2) to create new user:

userRouter.post(
  "/register",async (request, response) => {

    // A request body is data sent by the client to your API.
    const newUser = new User({
      firstName: request.body.firstName,
      lastName: request.body.lastName,
      email: request.body.email,
      pin: request.body.pin,
    });

    const createdUser = await newUser.save();

    response.send({ createdUser });
  };
);


// 3) to update existing user:
// first we need to find that user and then update its info.

userRouter.post(
  "/update",async (request, response) => {
    const editUser = await User.find({ email: request.body.email });


    // When there are no matches find() returns [].
    // So we could not use the condition: if(!editUser){...}

    if (!editUser.length) {
      response.status(400).send({ message: "No User Found" });
    } else {
        editUser.firstName: request.body.firstName,
        editUser.lastName: request.body.lastName,
        editUser.pin: request.body.pin,

        const updatedUser = await editUser.save();

        response.status(201).send({ updatedUser });
    }
  };
);


// 4) to delete a user:
// first we need to find that user and then delete it.

userRouter.delete(
  "/delete",async (request, response) => {
    const deleteUser = await User.find({ email: request.body.email });


    if (!deleteUser.length) {
      response.status(400).send({ message: "No User Found" });
    } else {
        const userDeleted = await deleteUser.deleteOne();

        response.status(201).send({ message: "User removed" });
    }
  };
);

export default userRouter;

Now it's possible to make request to server for desired data, such as:

GET request to fetch all users: /api/users/seed


Credit/Sources

Thank you to the author of this article posted in Medium.com, for helping me understand how to structure web app integration with MongoDB using Mongoose!

Author

I am a new web developer learning MERN stack applications

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment