Coder Social home page Coder Social logo

toeatly_mongoose's Introduction

toEatly with Mongoose

Can you modify this CRUD app to use MongoDB?

##First things first: Install Party!

We need to use brew to install our new MongoDB database system!

From the console:

brew install mongodb

Now we need to create a directory for MongoDB to save and store data.

From the console:

sudo mkdir -p /data/db

Let's ensure that the folder permissions allow us to read and write to our newly made directory.

From the console:

sudo chown -R $USER	/data/db

You may also want to do a global install of nodemon. Nodemon automatically restarts our server when we make any changes in our source code.

npm install -g nodemon

Project Setup

Install application packages/dependencies:

npm install

Run the server:

mongod
nodemon index.js

Instructions

Our foods data is currently hardcoded in server.js and lives in active memory. When the server restarts, we lose our data. Your goal is integrate MongoDB into your routes so that you can permenantely save/persist data across sessions.

By the end of this process we should have the following application directory (note the models folder):

    models/
        index.js
        food.js
    public/
        css/
            main.css
        js/
            app.js
    views/
        index.html
    .gitignore
    server.js
    package.json
    README.md    

NOTE: One important difference between the toEatly_mongoose project and the original toEatly project is that we have globally changed foods.id to foods._id because of a strict naming convention in mongoose

Step 1. Create the Food Model / Schema

Install mongoose inside our project directory:

npm install --save mongoose

Next we want to create our models directory (this is where our database magic will happen):

mkdir models
touch models/food.js

Let's create Food model. A Food has a few different characteristics: name, and yumminess.

To create a Food model we have to use a Schema in models/food.js

var mongoose = require("mongoose");

var Schema = mongoose.Schema;
var FoodSchema = new Schema({
    name: String,
    yuminess: String
});

Here is a link to all of the different datatypes we can use in a Schema

Finally, at the bottom of food.js we need to create the Food model and export it (that way we can use it in other parts of our app):

var Food = mongoose.model('Food', FoodSchema);
module.exports = Food;

Step 2. Connect to the Database

Next, let's wire it all up:

touch models/index.js

Inside of models/index.js we need to create and connect to our mongoose database (this is where the magic happens):

var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/to_eatly_app");

module.exports.Food = require("./food");

Step 3. Sanity Check - Plug the database into node

Now that we've done all the hard work, all that's left is to "require" our models.

If you open the node REPL by typing node in the terminal, you can do the following:

var db = require('./models');

db.Food.create({name: "foo", tastiness: "very"}, function (err, food) {
    if (err) { return console.log(err); };
    console.log(food);
});

Now you should be able to type the following, and see our new food item:

    db.Food.find({}, function(err, foods){
        if (err) { return console.log("Error:  No Food db created."); }
        console.log(foods)
    })

If this does not work, the solutions branch includes a more complete seed.js file which you can copy and run from the CLI:

node seed.js

Now let's do it in the express app!

Step 3. Plug the database into express

Add this line near the top of server.js:

var db = require('./models');

Challenge

The time has come for us to swap out all our hardcoded data for live data from our database. This will require us to methodically alter each route to accomodate the new data store. Where should we start!?

Hint: Here's what our index route might look like:

app.get("/allthefoods", function(req, res){

    db.Food.find({}, function(err, foods){
        if (err) {
            console.log("Error! Could not find foods.");
            return res.sendStatus(400);
        }
        res.send(foods);
    })

})

toeatly_mongoose's People

Contributors

jlopker avatar bgveenstra avatar benhulan avatar ilias-t avatar

Watchers

James Cloos avatar Angelo avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.