Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Answers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
1. Describe the following: `DataBase`, `Collection` , `Document`
DataBase: Is a large assortment of Collections and Documents; it represents the largest group in the mongo file structure.
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👌

Collection: Is a subset of a database; it is the second tier in the mongo file structure; and represents a group of documents.
Document: Is the third tier in the mongo file structure; and represents the smallest part of the mongo file structure; a document is the specific data that is saved and retrieved.

Document is the data; a Collection is a way for mongo to organize documents and finally a Database is the housing unit for all the collections and subsequent documents.

1. Describe how one can achieve the pattern of _relationships_ in MongoDB. What
needs to take place at the schema level? How do we _'fill'_ in the
appropriate relational data using mongoose?

Relationships can be built in MongoDB by including models within models that can be accessed by Mongoose through the connect method within the top level of the server. After references have been created in the models; the data can be pulled and displayed dynamically using the .populate method that mongoose provides.

1. Explain a way to break up an API into Sub-Applications, which tool did we use to do that?
An API is split into Sub-Pages using dynamic and static URLs that communicate with the UI to display the appropriate information that the user is requesting. Target server/database calls based on the route the user selects allows for an organized display of relevant information.
9 changes: 9 additions & 0 deletions Budget/Budget.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const mongoose = require('mongoose');

const Budget = new mongoose.Schema({
title: String,
budgetAmount: Number

});

module.exports = mongoose.model('Budget', Budget);
20 changes: 20 additions & 0 deletions Budget/budgetRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const express = require('express');

const Budget = require('./Budget.js');

const router = express.Router();

router.post('/', (req, res) => {
const {title, budgetAmount} = req.body
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we're not using the variables title and budgetAmount for anything, we could just pass req.body to our new Budget: const budget = new Budget(req.body) and skip the whole object destructuring thing.

const newBudget = { title, budgetAmount}
const budget = new Budget(newBudget)
.save()
.then((response) => {
res.status(200).json(response)
})
.catch((error) => {
res.status(500).json(error)
})
})

module.exports = router;
9 changes: 9 additions & 0 deletions Category/Category.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const mongoose = require('mongoose');
const ObjectId = mongoose.Schema.Types.ObjectId;

const Category = new mongoose.Schema({
title: String

});

module.exports = mongoose.model('Category', Category);
30 changes: 30 additions & 0 deletions Category/categoryRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const express = require('express');

const Category = require('./Category.js');

const router = express.Router();

router.get('/', (req, res) => {
Category.find().select('title -_id')
.then((categories) => {
res.status(200).json(categories)
})
.catch((error) => {
res.status(500).json(error)
})
})

router.post('/', (req, res) => {
const {title } = req.body
Copy link
Copy Markdown
Author

@frankfaustino frankfaustino Jun 15, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Character spacing here is a bit off. According to Airbnb's styleguide (https://github.com/airbnb/javascript#whitespace--in-braces), there should be spaces inside curly braces.

Also, we don't need to use object destructuring here.

const newCategory = { title}
const category = new Category(newCategory)
.save()
.then((response) => {
res.status(200).json(response)
})
.catch((error) => {
res.status(500).json(error)
})
})

module.exports = router;
18 changes: 18 additions & 0 deletions Expense/Expense.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const mongoose = require('mongoose');
const ObjectId = mongoose.Schema.Types.ObjectId;

const Expense = new mongoose.Schema({
amount: Number,
description: String,
budget:[{
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since Expenses are many-to-one relationship with Budgets, this budget property shouldn't be an array.

type: ObjectId,
ref: "Budget"
}],
category:[{
Copy link
Copy Markdown
Author

@frankfaustino frankfaustino Jun 15, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, there are many Expenses per Category, but only one Category for each, so this property shouldn't be in an array.

type: ObjectId,
ref: "Category"
}]

});

module.exports = mongoose.model('Expense', Expense);
32 changes: 32 additions & 0 deletions Expense/expenseRouter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const express = require('express');

const Expense = require('./Expense.js');

const router = express.Router();

router.get('/', (req, res) => {
Expense.find()
.select("description amount -_id")
.populate('budget', "title budgetAmount -_id")
.populate('category', "title -_id")
.then((expense
) => {
res.status(200).json(expense
)
})
})

router.post('/', (req, res) => {
Copy link
Copy Markdown
Author

@frankfaustino frankfaustino Jun 15, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of sending the budget and category ObjectId along with the POST request, we can send a POST request that looks like this:

{
	"amount": 35,
	"description": "potatoes",
	"budget": "Monthly Spending",
	"category": "Groceries"
}

In order to do that, we need to add some logic to our route:

.post((req, res) => {
  let { amount, budget, category, description } = req.body

  budget = Budget.findOne({ title: budget })
  category = Category.findOne({ title: category })

  Promise.all([budget, category])
    .then(([budget_id, category_id]) => {
      const expense = new Expense({
        amount,
        budget: budget_id,
        category: category_id,
        description
      })

      expense.save()
        .then(response => res.status(201).json(response))
        .catch(err => res.status(500).json(err)))
    })
    .catch(err => res.status(500).json(err))
  })

We have to get budget and category with the findOne method, then using Promise.all, we grab the ObjectId for each from the response from MongoDB, then create our new Expense.

const { amount, description, budget, category } = req.body
const newExpense = { amount, description, budget, category }
const expense = new Expense(newExpense)
.save()
.then((response) => {
res.status(200).json(response)
})
.catch((error) => {
res.status(500).json(error)
})
})

module.exports = router;
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@
"keywords": [],
"author": "Lambda School",
"license": "ISC",
"dependencies": {},
"dependencies": {
"express": "^4.16.3",
"mongoose": "^5.1.4"
},
"devDependencies": {
"nodemon": "^1.17.2"
}
Expand Down
19 changes: 19 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,27 @@
const express = require('express'); // remember to install your npm packages
const mongoose = require('mongoose');

const server = express();

const budgetRouter = require('./Budget/budgetRouter')
const categoryRouter = require('./Category/categoryRouter')
const expenseRouter = require('./Expense/expenseRouter')

mongoose.connect('mongodb://localhost/budget')
.then(() => {
console.log('Sucessfully connected to MongoDb')
})
.catch(() => {
console.log('MongoDb connection failure')
})

// add your server code
server.use(express.json())

server.use('/api/budgets', budgetRouter)
server.use('/api/categories', categoryRouter)
server.use('/api/expenses', expenseRouter)


const port = process.env.PORT || 5000;
server.listen(port, () => {
Expand Down
Loading