0% found this document useful (0 votes)
131 views

Complete Backend Server Side Using Mongoose, Mongodb, Mongoose Compass, Postman, & Axios

This document outlines the setup and implementation of a backend server using Express, Mongoose, MongoDB, and middleware. It describes creating models, routes, and controllers for cats and agencies. The server connects to a MongoDB database, implements GET, POST, PUT, and DELETE requests, and uses Mongoose to define schemas and models. It also includes middleware for logging requests and a client folder setup to connect the frontend application.

Uploaded by

LelanaVilla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
131 views

Complete Backend Server Side Using Mongoose, Mongodb, Mongoose Compass, Postman, & Axios

This document outlines the setup and implementation of a backend server using Express, Mongoose, MongoDB, and middleware. It describes creating models, routes, and controllers for cats and agencies. The server connects to a MongoDB database, implements GET, POST, PUT, and DELETE requests, and uses Mongoose to define schemas and models. It also includes middleware for logging requests and a client folder setup to connect the frontend application.

Uploaded by

LelanaVilla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

COMPLETE BACKEND SERVER SIDE USING MONGOOSE, MONGODB,

MONGOOSE COMPASS, POSTMAN, & AXIOS

INDEX.JS
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const logger = require("./middleware/logger.js");


const catRouter = require("./routes/cats.js");
const agencyRouter = require("./routes/agencies.js");

const app = express();


const port = 8080;

//middleware
app.use(bodyParser.json());
app.use(logger);

//routes
app.use("/cats", catRouter);
app.use("/agencies", agencyRouter);

mongoose.connect("mongodb://localhost:27017/animals", (err) => {


if (err) console.error(err);
console.log("Connected to MongoDB");
})
app.listen(port, () => console.log("Server running on port " + port));

I​NSIDE ROUTES FOLDER-


cats.js
agencies.js

INSIDE CATS.JS:

1
const express = require(‘express’);
const catRouter = express.Router();

const CatModel = require("../models/cats.js");


const AgencyModel = require("../models/agencies.js");

//actual routes go here


catRouter.route("/")
.get((req, res) => {
CatModel.find(req.query)
.populate("agencyId")
.exec((err, foundCats) => {
if (err) return res.send(err);
res.status(200).send(foundCats)
});
})

//​POST
.post((req, res) => {
const newCat = new CatModel(req.body);
newCat.save((err, savedCat) => {
if (err) return res.send(err);
CatModel.populate(savedCat, { path: "agencyId" }, (err, popCat) => {
if (err) return res.send(err);
res.status(201).send(popCat);
});
});
});

// GET one request


catRouter.route("/:id")
.get((req, res) => {
CatModel.findOne({ _id: req.params.id })
.populate("agencyId")
.exec((err, foundCat) => {

2
if (err) return res.send(err);
if (!foundCat) return res.status(404).send({ message: "Cat not found" })
res.status(200).send(foundCat);
});
})
​ // DELETE one request
.delete((req, res) => {
CatModel.findOneAndRemove({ _id: req.params.id }, (err, deletedCat) => {
if (err) return res.send(err);
if (!deletedCat) return res.status(404).send({ message: "Cat not found" })
res.status(204).send();
})
})
//PUT one
.put((req, res) => {
CatModel.findOneAndUpdate({ _id: req.params.id }, req.body, { new: true })
.populate("agencyId")
.exec((err, updatedCat) => {
if (err) return res.send(err);
if (!updatedCat) return res.status(404).send({ message: "Cat not found" });
res.status(200).send(updatedCat);
})
})

module.exports = catRouter;
INSIDE /ROUTES/AGENCIES.JS:

const express = require(‘express’);


const agencyRouter = express.Router();

//GET ONE
const AgencyModel = require("../models/agencies.js");
agencyRouter.route("/")
.get((req, res) => {
AgencyModel.find(req.query, (err, foundAgencies) => {

3
if (err) return res.send(err);
res.status(200).send(foundAgencies);
});
})
//POST ONE
.post((req, res) => {
const newAgency = new AgencyModel(req.body);
newAgency.save((err, savedAgency) => {
if (err) return res.send(err);
res.status(201).send(savedAgency);
});
})

module.exports = agencyRouter;
INSIDE THE MODELS FOLDER-
agencies.js
cats.js
INSIDE MODELS/CATS.JS:

const mongoose = require(‘mongoose’);


const { Schema } = mongoose;

//Schema is a constructor
// determines the template for all documents in a collection

const catSchema = new Schema({


name: String,
breed: {
required: true,
type: String
},
age: Number,
adoptionStatus: {
type: String,
default: "not adopted"

4
},
agencyId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "agencies"
}
})

const CatModel = mongoose.model("cats", catSchema);

module.exports = CatModel;
INSIDE MODELS/AGENCIES.JS:

const mongoose = require(‘mongoose’);


const { Schema } = mongoose;

const agencySchema = new Schema({


name: String,
location: String
});

module.exports = mongoose.model("agencies", agencySchema);

INSIDE MIDDLEWARE FOLDER-


logger.js
INSIDE MIDDLEWARE/LOGGER.JS:

module.exports = (req, res, next) => {

const time = new Date().toLocaleTimeString();


console.log(req.method, time);
next();
}
INSIDE CLIENT FOLDER-
YOUR FRONT END SETUP SHOULD LIVE HERE

TO CONNECT YOUR LOCAL SERVER TO YOUR CLIENT SIDE SETUP YOULL NEED TO GO INTO
5
YOUR​ PACKAGE.JSON FILE ​INSIDE YOUR ​CLIENT FOLDER​ AND CREATE AN OBJECT CALLED
PROXY ​AND SET IT TO THE PORT OF YOU HAVE YOUR SERVER ON
EX:
"proxy": "​http://localhost:8080​"

Created April 2018 by Lelana Villa

You might also like