Friday, September 19, 2014

Hello, MongoDB

Update: Check out the accompanying Github repo to these posts about MongoDB/Mongoose.


Learning the MEAN stack is fun, especially Node and Angular.  There's a lot to get into just in those two parts, but eventually you're going to want to save some data.  (If not, try out my npm module that fakes persistence.)

So let's learn about the "M."

MEAN is supposed to be MongoDB, Express, AngularJS, and Node, but the "M" really seems to stand for Mongoose, a modeling system.  It's MongoDB underneath, but you don't really have to deal with it directly.


Mongoose Essentials

Define a Schema

The schema describes the object you're going to work with.
var mongoose = require('mongoose');

var dudeSchema = mongoose.Schema({
    name: String,
    age: Number,
    height: Number,
    isMale: Boolean
});

Create a Model

Use your schema to create a model.

var Dude = mongoose.model('Dude', dudeSchema);

Use the Model for CRUDing

var gw = new Dude({
    isMale: true,
    name: 'George Washington'
});

gw.save(function (err, run) {
    if (err) {
        res.status(500).send(err);
    } else {
        res.json(run);
    }
});
This is just the very basics to help you get your bearings.  We'll get more complex later.

references

No comments:

Post a Comment