Monday, November 28, 2011

Node.js - Day 2

Day 2 - MongoDB

Despite being skeptical about MongoDB, I think it is worth going the whole hog and getting the full experience.

First, my example data model sketch (something like a survey engine):

{
"Q1": {
"sort": "single",
"text": "What is your age?",
"choices": [
        { "code": "Q1", "text": "18 to 29" },
        { "code": "Q1", "text": "30 to 39" }
]
},
"status": "unseen",
"optional": false,
"answer": "",
"next": "end"
}
}


To minimise frustration with schema definition I installed Mongoose following Googles advise, and I'm on my way!

Mongoose seems to have a concept of a document Schema which looks handy - converting my data model sketch into a schema:

db.js


exports.create_schema = function(mongoose) {


var Schema = mongoose.Schema;
var Docs = {};


var QuestionChoice = new Schema({
code: String,
text: String
});


var Question = new Schema({
sort: String,
text: String,
choices: [QuestionChoice],
status: String,
optional: Boolean,
answer: String,
next: String
});


var Survey = new Schema({
questions: [Question]
});


Docs.Survey = mongoose.model("Survey", Survey);
Docs.Question = mongoose.model("Question", Question);
Docs.QuestionChoice = mongoose.model("QuestionChoice",  QuestionChoice);

return Docs;
}

This was a little frustrating - I wanted to assign Survey, Question, and QuestionChoice to exports,  but the Node.js docs say that exports should only be assigned to on the initial require("package.js").


Adding to init.js:


var mongoose = require("mongoose");

mongoose.connect('mongodb://localhost/test');


var Docs = db.create_schema(mongoose);

var survey1 = new Docs.Survey();

var question1 = new Docs.Question();
question1.code = "Q1";
question1.text = "Question Text";

survey1.questions.push({"text":"Question"});

survey1.save(function (err) {
if(err) {
console.log("Unable to save survey.");
} else {
console.log("Saved survey.");
Docs.Survey.findOne({}, function(err, docs) {
console.dir(docs.questions);
});
}
});

Sadly, this is not working - docs.questions is showing as []. This is frustrating, and it's well past midnight, so I'm going to try to fix this on Day 3.

1 comment:

  1. Would be nice with a like button :)
    Im still following you, thanks to reddit.

    Were so sad when I didnt see any post on friday.

    ReplyDelete