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
17 changes: 17 additions & 0 deletions api/models/books.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const mongoose = require('mongoose');

const schema = new mongoose.Schema({
title: {
type: String,
required: true
},
published: Number,
authors: [{
name: String,
dob: Number
}]
}, {
timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }
});

module.exports = mongoose.model('Books', schema)
55 changes: 55 additions & 0 deletions api/routes/books.authors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const router = require('express').Router({mergeParams: true})
const Books = require('../models/books')


Copy link

Choose a reason for hiding this comment

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

Because of how you defined your routes in the books.js route file most of the code in this file will never be called. See my other comment.

Copy link
Author

Choose a reason for hiding this comment

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

O jeez! That saved me, I felt like I was going crazy! Thank you for your help!

router.get('/', async (req, res, next) => {
const status = 200
const {authors} = await Books.findById(req.params.bookId).select('authors')

res.json({ status, authors })
})

router.post('/', async (req, res, next) => {
const status = 201
const books = await Books.findById(req.params.bookId)

books.authors.push(req.body)
await books.save()// ok, it updates an existing document or inserts a new document, depending on its document parameter.

const author = books.authors[books.authors.length -1]
res.json({ status, author })
// ok, so res.status(status) is declaring that the current status of res is "status", and the .json() parses that data as JSON.
})

router.get('/:id', async (req, res, next) => {
const status = 200
const {authors} = await Books.findById(req.params.bookId).select('authors')
const author = authors.id(req.params.id)

res.json({ status, author })
})

router.put('/:id', async (req, res, next) => {
Copy link

Choose a reason for hiding this comment

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

This code looks good but is never running because of the issue posted below.

Copy link
Author

Choose a reason for hiding this comment

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

I think this is now fixed.

const status = 200
const books = await Books.findById(req.params.bookId)
const author = books.authors.id(req.params.id)
//here "id" is the name of the parameter, and we are identifying the id of the author through the param that we specify. Could you break this down a little? It has some layers I am not following.
Object.assign(author, req.body)
// ok, so "author" is the target, and "req.body" is the source. We are forever changing "author" by copying/adding the properties from "req.body" to "author"
await books.save()

res.status(status).json({ status, author });
})

router.delete('/:id', async (req, res, next) => {
const status = 200
const books = await Books.findById(req.params.bookId)
const author = books.authors.id(req.params.id).remove()
await books.save()

res.status(status).json({ status, author });
})

module.exports = router

// I am confused about needing this file, because I was able to update the author name before exicuting this code. UPDATE: Nope, i actually was NOT able to do this before this code. Still confused on why I cannot GET /api/books/:bookId/authors/:authorId
67 changes: 46 additions & 21 deletions api/routes/books.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const router = require('express').Router()
const { generate: generateId } = require('shortid')
const Books = require('../models/books')

const books = [
{
Expand All @@ -26,48 +27,72 @@ const books = [
}
];

router.get('/', (req, res, next) => {
router.get('/', async (req, res, next) => {
const status = 200
const response = books
const response = await Books.find(req.query).select('_id title published authors')

res.json({ status, response })
})

router.post('/', (req, res, next) => {
router.post('/', async (req, res, next) => {
const status = 201

books.push({ id: generateId(), ...req.body })
const response = books

res.json({ status, response })
try {
const response = await Books.create(req.body)
res.json({ status, response })

} catch (error) {
error.status = 400
error.message = 'Invalid data. Please try again.'

next(error)
}

})

router.get('/:id', (req, res, next) => {
router.get('/:id', async (req, res, next) => {
const status = 200
const response = books.find(({ id }) => id === req.params.id)
const response = await Books.findById(req.params.id).select('_id title published authors')

res.json({ status, response })
})

router.put('/:id', (req, res, next) => {
router.put('/:id', async (req, res, next) => {
const status = 200
const response = { id: req.params.id, ...req.body }
const single = books.find(({ id }) => id === req.params.id)
const index = books.indexOf(single)

books.splice(index, 1, response)
const query = {_id:req.params.id}
const options = {new:true}
const response = await Books.findOneAndUpdate(query, req.body, options)

res.json({ status, response })
})

router.delete('/:id', (req, res, next) => {
router.delete('/:id', async (req, res, next) => {
const status = 200
const response = books.find(({ id }) => id === req.params.id)
const index = books.indexOf(response)

books.splice(index, 1)
const response = await Books.findOneAndDelete({ _id: req.params.id })

res.json({ status, response })
})

// router.get('/:bookId/authors/:id', async (req, res, next) => {
// const status = 200
// const response = await Books.authors.findById(req.params.id)

// res.json({ status, response })
// })

// router.put('/:bookId/authors/:id', async (req, res, next) => {
// const status = 200
// const query = {_id:req.params.id}
// const options = {new:true}
// const response = await Books.authors.findOneAndUpdate(query, req.body, options)

// res.json({ status, response })
// })

// router.delete('/:bookId/authors/:id', async (req, res, next) => {
// const status = 200
// const response = await Books.authors.findOneAndDelete({ _id: req.params.id })

// res.json({ status, response })
// })

module.exports = router
3 changes: 2 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const app = express()

// Database Connection
if (MONGO_DB_CONNECTION) {
mongoose.connect(MONGO_DB_CONNECTION, { useNewUrlParser: true })
mongoose.connect(MONGO_DB_CONNECTION, { useNewUrlParser: true, useFindAndModify: false })
console.log('Connected to database...')
} else {
console.log('Could not connect to database!')
Expand All @@ -17,6 +17,7 @@ app.use(require('body-parser').json())

// Routes
app.use('/api/books', require('./api/routes/books'))
app.use('/api/books/:bookId/authors', require('./api/routes/books.authors'))

// Not Found Handler
app.use((req, res, next) => {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"description": "",
"main": "app.js",
"scripts": {
"debug": "PORT=5000 node --inspect app.js",
"dev": "nodemon app.js"
},
"keywords": [],
Expand Down