-
Fork and clone this repository.
-
Make a branch for your work using the command
git checkout -b my-work-sprint-1
. This branch will house the work that you have done on sprint 1.
- Take a few minutes to familiarize yourself with your surroundings and navigate the file structure of this app. You should see a few routes listed in
server.js
; a basic front-end using them, a few files in public including your front-end JavaScript.
"Hmm", you think to yourself, "this app seems to be a books app."
- Open up your browser and startup the server. Take a look at the books on the front-end.
You didn't forget to
npm install
did you?
-
Open up
server.js
and take a look at the hard-coded books data. You should see an array of book objects in there calledbooks
. -
You should also already see that there are routes to create (POST) new books, get a list of books (GET index), get a single book (GET show) and edit (PUT) and delete (DELETE) books. -- Notice they're all manipulating the
books
array.
Arrays are no longer adequate as a data-store. They lose their data whenever the server is shut down, they don't support backups unless you copy the file, and new elements never get saved in the file. Plus, all the cool kids are using databases.
Let's replace that array with a database. We'll create a booksSchema and Books model.
First off let's setup mongo and mongoose.
-
Install mongoose into this repo's package.json:
npm install --save mongoose
-
Create a new file
models/book.js
. We'll create a schema and model for books in this file! -
Our books will have the following attributes:
- title
- author
- image (use a string for this)
- releaseDate
Let's create a schema using these properties. Check out the different mongoose schema types here, but use String
for the above attributes:
// book.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BookSchema = new Schema({
title: String,
// you should fill the rest of this in
});
- Next let's create the
Book
model from the schema.
var Book = mongoose.model('Book', BookSchema);
- Finally we'll need to export Book from this module (that's this file). You can export it at the very end of the file by doing:
module.exports = Book;
- We've already provided a
models/index.js
for you to use. Examine it to see that it already:
- requires mongoose
- connects to a local book-app database URI
index.js
will import each model and export an object calledexports
with keys representing each of our models. That way we canrequire
the entire directory and get all of our models! Go ahead and import and export yourBook
model inindex.js
.
// models/index.js
var BookModel = require("./book.js");
module.exports = {Book: BookModel}
- Now if someone were to
require('./models')
they'd gain access to this book database model.
Here's a module example:
├── models
│ ├── index.js
│ ├── gargoyle.js
│ ├── gnome.js
│ ├── goblin.js
Inside index.js
we require each of the other files and export it as one object:
// models/index.js
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/book-app");
// the mongoose.connect line above needs to happen exactly once in your code
// move it from book.js to index.js :)
var GargoyleModel = require("./gargoyle.js");
var GoblinModel = require("./goblin.js");
var GnomeModel = require("./gnome.js");
module.exports = {
Gargoyle: GargoyleModel,
Goblin: GoblinModel,
Gnome: GnomeModel
}
In the end this means that when you require ./models
in server.js
you get back an object like
{ Gargoyle: Model, Goblin: Model, Gnome: Model }
- Take a quick look in
seed.js
. You should see that it does arequire('./models');
and then later usesdb.Book.create
to load some data into the database. (You might also notice that it tries to clear thebook-app
database first by deleting all the records.)
What's a seed-file, you ask?
A seed file is a file used to load pre-made data into our database. It lets us start up our app without having to key in starter data each time.
- Try running
node seed.js
in your terminal. If you're not seeingcreated X books
, then something might be going wrong in yourbook.js
file. Make suremongod
is running! You can't seed your database if it isn't up and running.
Here's an example of what your book.js
could look like:
// entire book.js so far
var mongoose = require('mongoose');
var BookSchema = new mongoose.Schema({
title: String,
author: String,
image: String,
releaseDate: String
});
var Book = mongoose.model('Book', BookSchema);
module.exports = Book;
- You can use the Mongo shell to check what's now in your database, or start interacting with it through the server files. If you got an error message above, FIX IT BEFORE YOU MOVE ON. If you're stuck, ask for help.
Next we'll start to use our new model in server.js
.
-
Open
server.js
. -
Add the correct
require
statement toserver.js
to import your models module:var db = require('./models')
. This should go near the top as part of the "SETUP and CONFIGURATION". -
Delete the hard-coded books array. We'll start to replace each route with the correct code to use the database instead. From now on, when we want to get to a book, we'll use mongoose methods and access
db.Books
. -
Find the books index route and replace it with the following code:
// server.js
app.get('/api/books', function (req, res) {
// send all books as JSON response
db.Book.find(function(err, books){
if (err) {
console.log("index error: " + err);
res.sendStatus(500);
}
res.json(books);
});
});
-
Restart your server. Debug any error messages you see.
-
If you've successfully seeded your database and debugged your code, you should see all the books from
seed.js
when you refresh the page.
On your own, use mongoose CRUD methods to refactor the other /api/books*
routes to get data from your database.
Make sure you look back to the notes or the Mongoose documentation for info on important model methods like:
find
findOneAndRemove
new
save