703 964 8217

Home » Blog » Node – Express – Neo4J : Getting Started

Node – Express – Neo4J : Getting Started

Goal:

To develop a Node Express Application that connects to a Neo4J Graph Database and leverages Cypher Queries to retrieve node data and display in a Jade Template.

Secondary Goal:

Learn

  • Cypher and Neo4j Queries.
  • Node Development and Deployment.
  • Express capabilities and Jade Template Engine.

Deployed Website:

A published application is available at: http://nodeexpressneo4j.azurewebsites.net/

screen-shot-2016-11-12-at-6-25-55-pm

Resources:

  1. New to Node / Express / Jade:

I found this instructional video useful for understanding the basics of Node and Express and how this whole things ties up together. Also if you get stumped by Jade (now Pug) and UI Templating engines, both the speakers have done a great job, making sure you understand what is happening under the hood.

https://mva.microsoft.com/en-US/training-courses/using-node-js-with-visual-studio-code-13920?l=nSEpCdzbB_001937557

  1. Neo 4j Database Instance

Ended up using GrapheneDB as provider for a Neo4J Instance The sandbox environment is free and is ideal for getting started and a lab environment. http://www.graphenedb.com/pricing

Also decided to use the Account Holders defined in this fairly involved starter Graph Dataset available at: https://github.com/neo4j-examples/graphgists/blob/master/fraud/bank-fraud-detection.adoc

  1. Development Environment:

I am a big fan of Visual Studio and have always considered it a great (though pricey) IDE. So I decided to stick with Visual Studio.

  • Node for Visual Studio Tools:

Here is a detail link to setting up Node for Visual Studio Tools in your environment.

https://github.com/Microsoft/nodejstools

Helps you debug code and provides Node – Express Project out of the box. The Green Arrow or F5 starts a Node Console and brings up a browser. You got to say YAYY!!!!

  • Non Visual Studio

Don’t be disappointed if you are Mac kind of a guy and love doing things from a console. There are several YoMan generators for you.

https://github.com/petecoop/generator-express

  1. Deployment:

Why keep it to yourself. Showcase it on the WWW for FREE!!!. If you have a Microsoft Azure Account, you get 10 websites for free. Here are your detailed instructions.

https://azure.microsoft.com/en-us/documentation/articles/app-service-web-nodejs-get-started/

If you have already created a project using Visual Studio and would simply like to add the code to Source Control and push to Azure, start at Step 4.

Development Gotchas

I have always believed in learning by example and feel it’s always good to learn by doing things in the code editor so this section is not going to be developed as cook book. I am going to highlight some of the things I have learned as I played with the application.

Node for Visual Studio Tools

A typical node application has a server.js or an app.js file. Please review this file carefully. Out of the box template in Visual studio creates an app.js file. The file has all the necessary require statements and all the routing information.

Cypher and Neo4J Queries

neo4jquery2

neo4j-queries

Neo4J in Javascript

I have used the neo4J driver npm package in my project to connect to the database. This code was mainly based upon the example code available here: https://github.com/neo4j/neo4j-javascript-driver

exports.about = function (req, res) {
    var driver = neo4j.driver("bolt://URL:PORT", neo4j.auth.basic("MoviesDB", "PWD"));
    // Create a session to run Cypher statements in.
    // Note: Always make sure to close sessions when you are done using them!
    var session = driver.session();
    // Run a Cypher statement, reading the result in a streaming manner as records arrive:
    session
   .run("MATCH (a:AccountHolder )  Return a")
  .subscribe({
        onNext: function (record) {
            console.log(record._fields);
        },
        onCompleted: function () {
            // Completed!
            session.close();
        },
        onError: function (error) {
            console.log(error);
        }
    });
};

Adding new Code and Routes

I took up the challenge of not writing code in the existing index file and instead decided to explore adding code in a separate file and bringing it together. I created a about.js in the routes folder and copied content from index.js. Renamed the exports.index method to be exports.about method and retrieved information about the AccountHolders Node in the Neo4j DB.

Here are the new contents of my about.js file.


exports.about = function (req, res) {
    var driver = neo4j.driver("bolt://URL:PORT", neo4j.auth.basic("MoviesDB", "PWD"));
    // Create a session to run Cypher statements in.
    // Note: Always make sure to close sessions when you are done using them!
    var session = driver.session();
    var persons = [];
    var fields = [];
    // Run a Cypher statement, reading the result in a streaming manner as records arrive:
    session
  .run("MATCH (a:AccountHolder )  Return keys(a), a")
  .subscribe({
        onNext: function (record) {
            persons.push(record._fields[1].properties);
            fields = record._fields[0];
            console.log(record._fields);
        },
        onCompleted: function () {
            // Completed!
            session.close();
            res.render('about', { title: 'Account Holders', year: new Date().getFullYear(), people: persons, fields: fields });
        },
        onError: function (error) {
            console.log(error);
        }
    });

};

Now lets manipulate the routes in the app.js file (yes you guessed it right!!!). Now that we added a new about.js file in the routes folder, we need to require it in the app.js file.

var about = require('./routes/about.js');

Now since we need our default page to be the call to the about.about method, we can add the following route (or alter the existing route information) with the following code.

app.get('/', about.about); // / refers to the default route.

Note about.about refers to the controller method that was exposed from about.js file.

Adding New Jade Template

Before you start working with templates, please understand the code statement in the about.js file above

res.render('about', { title: 'Account Holders', year: new Date().getFullYear(), people: persons, fields: fields });

Here the Response is going to render to “about” template and is going to pass back the following data: title, year, people and fields. How does the express framework know how to find the template? Refer the app.js again.

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

So first thing that you need to do is create a file called about.jade inside the Views folder.

extends layout
block content
    div.container
        div.row
            div.col-sm-8
              h2 #{title}
              h3 #{message}
              a.btn.btn-primary(href='/about/0' )
                span.glyphicon.glyphicon-plus 
              table.table.table-hover.table-condensed
                thead
                  tr
                    th First Name
                    th Last Name
                    th 
                tbody
                  each person, i in people
                    tr
                      td #{person.FirstName}
                      td #{person.LastName}
                      td 
                         a(href='/about/' + person.UniqueId )
                            span.glyphicon.glyphicon-edit

The about.jade begins by extends layout. Remember Master Page; that is exactly this is. The layout is defined in the views\layout.jade. Block content on the next line emphasizes that the content block in the layout.jade template will have the following content. ContentPlaceHolders anybody? The rest of the handlebar syntax is fairly common and self-exploratory.