Cookie Notice

As far as I know, and as far as I remember, nothing in this page does anything with Cookies.

2014/01/30

You Had ONE Job, Mongoose.js Documentation

Source
I'm trying to learn Node.js, MongoDB and Mongoose.js as an ORM connecting the two. I don't know what I'm doing yet, going through the early example code. I come to this as a reasonably experienced hand with Perl and MySQL. The first thing people write is a "Hello World" application, where you give it an input, commonly your name, and it gives you an output. In data, the four actions you want are Create, Read, Update and Delete, often used as CRUD. When trying out a data-storage system, you want to be able to Hello World your data.

The following is code adapted from the front page of Mongoosejs.com and the first link to documentation.

#!/usr/bin/js

/*
 * test_mongo.js
 *  adapted from mongoosejs.com
 *  
 * Getting up to speed with MongoDB, Mongoose as an ORM, ORMs in general,
 * and Node.js. 
*/

// Testing direct from http://mongoosejs.com/

// initiallizing connection to MongoDB 
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/cats');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
    console.log( "Yay" );
    });

// Schema - what comes from DB
var kittySchema = mongoose.Schema({ name: String }) ; 
kittySchema.methods.speak = function () {
    var greeting = this.name
        ? "Meow name is " + this.name
        : "I don't have a name" ;
    console.log(greeting);
    } ;
kittySchema.methods.save = function ( err , cat ) {
    console.log( cat ) ;
    if ( err ) {
        console.log(err) ;
        }
    cat.speak() ;
    } ;

// Model - what we work with
var Kitten = mongoose.model('Kitten', kittySchema) ;
Kitten.find(function (err, kittens) {
    if (err) // TODO handle err
    console.log(kittens)
    })

// Objects - instances of models
var silence = new Kitten({ name: 'Silence' }) ;
var morris = new Kitten({ name: 'Morris' }) ;
var fluffy = new Kitten({ name: 'Fluffy' });
var blank  = new Kitten({ });

console.log( '------------------------' ) ;
silence.speak() ;
morris.speak() ;
fluffy.speak() ;
blank.speak() ;
console.log( '------------------------' ) ;
silence.save() ;
morris.save() ;
fluffy.save() ;
blank.save() ;
console.log( '------------------------' ) ;

process.exit(0) ;


save() doesn't seem to save, or do anything, really. speak() works, but why shouldn't it? The reason I'm doing this is so that Mongoose can stand between me and MongoDB. Mongoose has one job. The documentation has one job: to show people me how to do just that.

One Job!

No comments:

Post a Comment