Skip to content
Federico Fissore edited this page Jan 4, 2013 · 20 revisions

Simple blog tutorial with expressjs and OrientDB

In this tutorial we assume that you already have an understanding about how web sites works, about how javascript works and that you are interested about what and how OrientDB works with nodejs.

Prerequisites

In order to complete this tutorial, you need to have installed and working:

  • nodejs: check it with the command node -v (on my computer it prints v0.8.16). In order to install nodejs on your computer, follow the instructions.
  • expressjs: check it with the command express -V (on my computer it prints 3.0.5). In order to install express, type npm install -g express (may required root access).
  • OrientDB: we assume that it's running on your computer. In order to install it, follow the instuctions. This tutorial uses version 1.3.0.

The basics

First, let's make a bare minimum express js app. Open up a console/terminal and type

express --sessions tutorial

Then

cd tutorial
npm install -d
node app.js

Express will report

Express server listening on port 3000

head over here and see express working as expected.

Introducing OrientDB

Create an blog database on OrientDB: you can do that using OrientDB Studio or using the OrientDB console with the command

create database local:/home/federico/materiale/works_My/orientdb-graphed-1.3.0/databases/blog admin admin local

(don't forget to adjust the path)

Edit file package.json and add the following snippet to the list of dependencies:

"orientdb": "*"

Edit file app.js and add this require:

orientdb = require("orientdb")

Right after it, add the following code

// previous code omitted

var dbConfig = {
    user_name: "admin",
    user_password: "admin"
};
var serverConfig = {
    host: "localhost",
    port: 2424
};

var server = new orientdb.Server(serverConfig);
var db = new orientdb.GraphDb("blog", server, dbConfig);

db.open(function(err) {
    if (err) {
        throw err;
    }
    console.log("Successfully connected to OrientDB");
});

// subsequent code omitted

Go back to the terminal, interrupt node with CTRL+C, run npm install -d again to download OrientDB nodejs driver, then restart the app with node app.js. You'll now see:

Express server listening on port 3000
Successfully connected to OrientDB

Well done!

Making the routes use OrientDB

Right below the console.log statement in db.open callback, add this snipped

routes.init(db, function(err) {
    if (err) {
        throw err;
    }
});

Then open index.js in routes folder. At its top, add the line module.db = null;. Then put the following function at the end of the file

exports.init = function(orient, callback) {
    module.db = orient;
};

This way, our routes module now has a private db property that allows us to communicate with OrientDB.

Preparing the schema

We are going to programmatically add some classes to our blog database, but only IF they are missing.

Open file index.js in routes folder and add the following function

function ensureSchemaIsSetup(callback) {
    if (module.db.getClassByName("Post") === null) {
        module.db.createClass("Post", "OGraphVertex", callback);
    }
    if (module.db.getClassByName("Tag") === null) {
        module.db.createClass("Tag", "OGraphVertex", callback);
    }
}

Now get exports.init function and, below module.db assignement, call ensureSchemaIsSetup so that it now looks like this:

exports.init = function(orient, callback) {
    module.db = orient;
    
    ensureSchemaIsSetup(callback);
};

Listing blog posts

Open file index.js in routes folder and modify the index function so that it looks like:

exports.index = function(req, res) {
    module.db.command("select from Post order by creation_date desc", function(err, posts) {
        res.render("index", {
            title: "Express + OrientDB blog",
            posts: posts
        });
    });
};

The important code here is the usage of the command function: first argument is the query to execute, an optional callback is the second argument.

Then open file index.jade in views folder and modify it so that it looks like:

extends layout

block content
  h1= title
  p Welcome to #{title}
  if posts.length > 0
    each post in posts
      p 
        b= post.title
      p= post.text
      p= post.creation_date.toLocaleDateString()
  else
    h3 There are no posts in this blog!

Restart the app to see our blog complaining for having no blog posts to show. Well done for now: it's time make some new posts!

Inserting blog posts

Open file index.jade and append the following line

  a(href="/new_post") Insert new blog post

Refreshing the index, you should see a link pointing to http://localhost:3000/new_post.

Create a new file called new_post.jade in views folder. Type in the following code:

extends layout

block content
  h1= title
  form(action="new_post",method="post")
    p
      label Title
      input(name="title",type="text")
    p
      label Text
      textarea(name="text",rows="5",cols="40")
    input(type="submit")

Now open file index.js in routes folder and add two new functions:

exports.new_post_form = function(req, res) {
    res.render("new_post", { title: "New post" });
};

exports.new_post = function(req, res, next) {
    var post = {
        title: req.body.title,
        text: req.body.text,
        creation_date: new Date()
    };
    module.db.createVertex(post, { "class": "Post" }, function(err) {
        if (err) return next(err);
        res.redirect("/");
    });
};

The important code here is the createVertex function: first argument if the vertex data, then an optional hash of options (if you are using a specific class, you need to specify it here) and an optional callback.

Wire them to the router: open file app.js in the root folder and below line app.get('/users', user.list); add:

app.get('/new_post', routes.new_post_form);
app.post('/new_post', routes.new_post);

Now restart the application and try inserting some new posts. Is it working? Are posts sorted in reverse chronological order? Well done!

Clone this wiki locally