So you have been playing around with Node.js writing pretty little programs and marvelling at how awesome it is.  But then you realise, your newly acquired wizardry isn't that much fun if you cannot collect data, store it in a database, and do something useful with it. So you jump on your broom and start surfing the interwebs in search of a solution.
When you search the internet for a Node.js database solution you will quickly notice how popular NoSQL databases are. As someone who is new to Node.js it is easy to start believing that it only speaks to NoSQL databases or that it doesn't work well with SQL databases. I held this perception for quite a long time. Sometimes a SQL database may be a better solution for you, it is a good fit if you are dealing with a lot of relational data that requires complex queries. Node.js prides itself at being very efficient in performing IO intensive tasks - that includes communicating with both SQL and NoSQL databases. Ghost, one of the most prominent opensource Node projects, uses SQL databases. Today I will share with you how I use MySQL in my Node.js projects.
The standard way of connecting to a database in most platforms is through an ORM, it provides a nice API to interact with your programs. After doing some research I came across Bookshelf.js, it is described as a JavaScript ORM for Node.js, built on the Knex SQL query builder and designed to work well with PostgreSQL, MySQL, and SQLite3.
My decision to pick Bookshelf.js was influenced by the following reasons:
To get up and running you need to install Bookshelf.js and its dependencies.
npm install bookshelf mysql knex --save
Making a database connection is pretty straight forward, let's do it in app.js
:
var knex = require('knex')({
client: 'mysql',
connection: {
host : '<IP_ADDRESS>',
user : 'your_database_user',
password : 'your_database_password',
database : 'myapp_test',
charset : 'utf8'
}
});
var Bookshelf = require('bookshelf')(knex);
We need to be able to reuse the same connection throughout our application, make sure it is accessible globally.
The example that I am going to use to demonstrate how Bookshelf works is that of a blog post. We will create a blog post that includes author, category, and tags metadata.
Firstly, we need to create database tables, let's create a separate file and name it schema.js
. This file contains the schema for our database tables.
var Schema = {
users: {
id: {type: 'increments', nullable: false, primary: true},
email: {type: 'string', maxlength: 254, nullable: false, unique: true},
name: {type: 'string', maxlength: 150, nullable: false}
},
categories: {
id: {type: 'increments', nullable: false, primary: true},
name: {type: 'string', maxlength: 150, nullable: false}
},
posts: {
id: {type: 'increments', nullable: false, primary: true},
user_id: {type: 'integer', nullable: false, unsigned: true},
category_id: {type: 'integer', nullable: false, unsigned: true},
title: {type: 'string', maxlength: 150, nullable: false},
slug: {type: 'string', maxlength: 150, nullable: false, unique: true},
html: {type: 'text', maxlength: 16777215, fieldtype: 'medium', nullable: false},
created_at: {type: 'dateTime', nullable: false},
updated_at: {type: 'dateTime', nullable: true}
},
tags: {
id: {type: 'increments', nullable: false, primary: true},
slug: {type: 'string', maxlength: 150, nullable: false, unique: true},
name: {type: 'string', maxlength: 150, nullable: false}
},
posts_tags: {
id: {type: 'increments', nullable: false, primary: true},
post_id: {type: 'integer', nullable: false, unsigned: true},
tag_id: {type: 'integer', nullable: false, unsigned: true}
}
};
module.exports = Schema;
Pro Tip: Promises will save you a lot of time and headaches when dealing with databases in Node, my preferred flavour is when. Also install a utility library for doing common tasks, lodash
is one of the best.
npm install when lodash --save
We need another file for the code that creates our tables, let's call it migrate.js
. It requires knex
so let's copy the code that we wrote earlier and place it at the beginning of the file.
I also copied the createTable
function from the Ghost project, it accepts a tableName
string and returns a promise.
var knex = require('knex')({
client: 'mysql',
connection: {
host : 'localhost',
user : 'your_database_user',
password : 'your_database_password',
database : 'myapp_test',
charset : 'utf8'
}
});
var Schema = require('./schema');
var sequence = require('when/sequence');
var _ = require('lodash');
function createTable(tableName) {
return knex.schema.createTable(tableName, function (table) {
var column;
var columnKeys = _.keys(Schema[tableName]);
_.each(columnKeys, function (key) {
if (Schema[tableName][key].type === 'text' && Schema[tableName][key].hasOwnProperty('fieldtype')) {
column = table[Schema[tableName][key].type](key, Schema[tableName][key].fieldtype);
}
else if (Schema[tableName][key].type === 'string' && Schema[tableName][key].hasOwnProperty('maxlength')) {
column = table[Schema[tableName][key].type](key, Schema[tableName][key].maxlength);
}
else {
column = table[Schema[tableName][key].type](key);
}
if (Schema[tableName][key].hasOwnProperty('nullable') && Schema[tableName][key].nullable === true) {
column.nullable();
}
else {
column.notNullable();
}
if (Schema[tableName][key].hasOwnProperty('primary') && Schema[tableName][key].primary === true) {
column.primary();
}
if (Schema[tableName][key].hasOwnProperty('unique') && Schema[tableName][key].unique) {
column.unique();
}
if (Schema[tableName][key].hasOwnProperty('unsigned') && Schema[tableName][key].unsigned) {
column.unsigned();
}
if (Schema[tableName][key].hasOwnProperty('references')) {
column.references(Schema[tableName][key].references);
}
if (Schema[tableName][key].hasOwnProperty('defaultTo')) {
column.defaultTo(Schema[tableName][key].defaultTo);
}
});
});
}
function createTables () {
var tables = [];
var tableNames = _.keys(Schema);
tables = _.map(tableNames, function (tableName) {
return function () {
return createTable(tableName);
};
});
return sequence(tables);
}
createTables()
.then(function() {
console.log('Tables created!!');
process.exit(0);
})
.catch(function (error) {
throw error;
});
Run the file from the command-line node migrate
. If everything went well you will see the text Tables created!!
.
Another Pro Tip: Ghost is an amazing piece of software, its code is clean and well written. When you get stuck with Bookshelf and cannot find an answer on Google, just dig through the code base and look at how Bookshelf is used. I find myself constantly referring to it for solutions.
Now back to app.js
- I only use Bookshelf in data structures, i.e, in my Models and Collections. Let's go ahead and create a few Models:
// User model
var User = Bookshelf.Model.extend({
tableName: 'users'
});
// Post model
var Post = Bookshelf.Model.extend({
tableName: 'posts',
hasTimestamps: true,
category: function () {
return this.belongsTo(Category, 'category_id');
},
tags: function () {
return this.belongsToMany(Tag);
},
author: function () {
return this.belongsTo(User);
}
});
// Category model
var Category = Bookshelf.Model.extend({
tableName: 'categories',
posts: function () {
return this.hasMany(Post, 'category_id');
}
});
// Tag model
var Tag = Bookshelf.Model.extend({
tableName: 'tags',
posts: function () {
return this.belongsToMany(Post);
}
});
Bookshelf is heavily influenced by Eloquent ORM and handles one-to-one, one-to-many, and many-to-many associations by defining relationships on Models. What is important to know is how Bookshelf handles these relationships under the hood. Let us look at some of the special properties and methods.
Defining a hasTimestamps
property in a model and assigning a value of true
has special effects. Upon creation or when updating, Bookshelf will automatically insert values for the created_at
and updated_at
columns.
The hasMany
method tells the current model that it has a one-to-many relationship with the model contained in its arguments.
The belongsTo
method tells the current model that it has a one-to-one or one-to-many relationship with the model contained in its arguments.
The belongsToMany
method tells the current model that it has a many-to-many relationship with the model contained in its arguments. This type of a relationship is joined through another table. In our example, the Post
model has a many-to-many relationship with the Tags
model. Bookshelf will assume that there is a table named posts_tags
- it joins the two table names with an underscore. This is all done under the hood, all you have to do is create the table and Bookshelf will do the rest.
In other relationships Bookshelf assumes that table names are plurals and that the foreignkey is the singular post-fixed with _id
. It uses the following format:<TableNameSingular>_id
. In our example, the author
method in the Post
model will be mapped to the User
model (where the table name is users
) through the foreignkey user_id
(substring user
is the singular of table name users
).
If your foreignkey and table name do not conform to the above convention you need to specify the foreignkey as a second argument like we did for the relationship between Posts
and Categories
.
Phew, hope that makes sense, if not leave a comment.
In the next post we will create a small API that uses our Models. Stay tuned.
Checkout the post that uses the Models to create a small API


The Exorcist (1973, 2000-reissue) 2 1/2 stars out of 4. Starring Ellen Burstyn, Linda Blair, Jason MIller, Max Von Sydow and Lee J. Cobb. Written by William Peter Blatty. Directed by William Friedkin. Rated R.
Time has not been kind to "The Exorcist."
What was controversial and stomach churning back in 1973 seems almost quaint today.
"The Exorcist" still packs a wallop, but it has been blunted because over the past 27 years our senses have been assailed with images much more horrifying - both on and off the screen - that our systems we have been dulled to the point of numbness.
It is ironic that the most uncomfortable scenes in "The Exorcist" have nothing to do with demonic possession; rather, they are the sequences set in the hospital where poor little Regan (Linda Blair) is put through various painful medical procedures to try to determine what is causing her spells and outbursts.
Nor does the addition of new scenes help the movie; it only makes it longer.
As a brash young reporter in Springfield, Ohio, I reviewed "The Exorcist" upon its initial release. I said then that the movie was overhyped, that it was nothing more than an overblown horror film. For my trouble, the irate local theater owner tried to get me banned from his movie houses. Not likely.

"The Exorcist" is a nerve jangler, to be sure, but it is neither the first nor last word in horror films. I still would rate such films as "Halloween" and the original "Alien" as much scarier outings than William Friedkin's frightfest.
"The Exorcist" offers many fine performances, including Ellen Burstyn, Jason Miller and especially young Blair. Friedkin's direction is crisp and keeps the audience at seat's edge.
But, unfortunately, the movie does seem dated. The jumping bed, the pea-soup vomit, Regan's spinning head, today look like what they are - movie trickery.
"The Exorcist" still is potent in some scenes, but overall the magic and mystery are gone.
Bloom is the film critic at the Journal and Courier in Lafayette, IN. He can be reached by e-mail at<EMAIL_ADDRESS>or at<EMAIL_ADDRESS>Reviews by Bob Bloom can be found on the Web at the Internet Movie Database: http://www.imdb.com/M/reviews_by?Bob+Bloom
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


Login with Google
Re-Authorize Google Continue!
Refresh Labels from Google Start Capture
Will Exclude Labels..
Included Labels..
Subject: {{ currentTask.report.sample.subject }}
These captured bundles are available for download, but not forever (I think 6 hours)
{{ bundle }}


"A Member of the Legislative Assembly
is a representative elected by the voters of a constituency to the legislature or legislative assembly of a sub-national jurisdiction."
6
Ward Members
MLA's
-
Kundan
Offline -
Kohli Sarthak
Available -
Chaitanya
Busy


Event Participation
Departments:
---Please Select Your Department---
Computer Science & Engineering
Mechanical Engineering
Civil Engineering
Chemical Engineering
Electrical Engineering
Science & Humanities
BVOC in Software
Events:
---Please Select Your Event---
Please Register before Participation if you haven't yet?
Click here


{% blocktranslate with name=object.name trimmed %} You've been invited to {{ name }}! {% endblocktranslate %}
{% blocktranslate with game_master=user.username place_name=object.place.name trimmed %} {{ game_master }} invites you to join into an epic quest in the world of {{ place_name }}. {% endblocktranslate %}
{% trans "check this world here"|capfirst %} {% url 'roleplay:place:detail' object.place.pk as place_link %} {{ object.place.name }}
{% blocktranslate with name=object.name trimmed %} The adventure of "{{ name }}" awaits for you! {% endblocktranslate %}
{{ scheme }}://{{ host }}{{ join_url }}


Legend: O/U: This is the line indicating the total number of points scored, predicted by Vegas
Pk: CCFW prediction that the teams will score more points ("O") or fewer points ("U") than the line
"*": Confidence of the CCFW prediction, 1 = low confidence, 5 = high confidence
Line: Vegas line indicating the predicted difference between the two teams' scores; negative number means
the home team is predicted to win, positive means the away team is predicted
to win
Pick: CCFW prediction as to which team will beat the Vegas Line
"*": Confidence of the CCFW prediction; 1 = low confidence, 5 = high confidence
Sort by:
Game Date
Home Team
Score
Away Team
Score
O/U
Pick
*
Line
Pick
*
Final Score
{{ x.GameDate }}
{{ x.HomeTeam }}
{{ x.HomeScore }}
-
{{ x.AwayTeam }}
{{ x.AwayScore }}
{{ x.OverUnder }}
{{ x.OUPick }}
{{ x.OUStar }}
{{ x.Line }}
{{ x.LinePick }}
{{ x.IsPositive }}
{{ x.LineDiff }}
{{ x.LineStar }}
{{ x.HomeFinal }}
-
{{ x.AwayFinal }}
*UTSA - Houston game was postponed due to Hurricane Harvey
*Arkansas St - Miami, FL game was cancelled due to Hurricane Irma
*Connecticut - USF game was postponed to Week #10 due to Hurricane Irma
*Florida - N. Colorado game was cancelled due to Hurricane Irma
*Florida St - UL Monroe game was postponed due to Hurricane Irma
*UCF - Memphis game was postponed due to Hurricane Irma
*Indiana - FIU game was cancelled due to Hurricane Irma
*UCF - Georgia Tech game was cancelled due to Hurricane Irma


It all began with my search for a healthier way of consuming the active ingredient in weed/hash: THC. Even using a bong was kinda hard om my throat since I have a mild form of asthma, so I tried various ways of consuming weed/hash. Hot chocolate milk with hash, weed butter, alcohol drinks, I tried it all but somehow they never worked the way they should with me. So finally after reading trough some scientific articles about extracting THC for medical purposes I stumbled upon methods for getting pure THC.
Although these methods were way too difficult/expensive for me to perform at home, using acetone which is highly flammable and concentrated sulfuric acid for example, I learned about a proces called decarboxylation: much of the THC in hemp is present in the form of the biologically inactive tetrahydrocannabinolic acid. By heating you can convert the THC acid (THCS) into THC and CO2. So after some thinking about ways too get that done I decided to use common olive oil as a carrier and way of heating for the THCS to convert into THC.
I ended up making a mixture of about 1 gram hash, 1 gram weed in a few tablespoons olive oil which I heated to 180 degrees celcius for about an hour till no more bubbles of CO2 appeared. And since a friend of mine swears by drinking olive oil as a way to avoid hangovers after drinking too much, I decided it couldn't be that bad to drink a bit of this mixture pure. Was I ever wrong.... first of all it tasted horrible! Even now, months later I still have shivers thinking about it... Somehow I managed to drink about three quarters of the mixture before I just couldn't take anymore. Far too much I realise now, but at that moment I wanted to really feel something unlike my other unsuccesfull attempts with the consuming of THC.
But, after an hour or two when the effects really started to kick in it seemed to have worked just great. I had the heaviest trip ever with tingles in my toes, fingers and the top of my nose but nothing I couldn't handle. After an hour or 5 however I became tired so I decided to sleep early. Like always I didn't have any trouble going to sleep and I can't even remember hitting the pillow with my head. Yet somehow it was a very restless and confusing night and when I finally did wake up (14 hours later!) I felt worse than ever... I just felt so dizzy, sluggish, sick and ready to puke that only getting from my bed must have taken me about half an hour. When I finally did make it to the bathroom, I had to lie down.
There I fell asleep again for an hour or two... The rest of the day I hardly can remember. I managed to eat something and for the rest I just sat quietly in a chair moving as little as possible to avoid puking from the dizziness. I wasn't tripping anymore, I just felt sick. And I kept feeling sick for the next three days! The days were just a blur... hours passing by, half sleeping, half awake. Finally after THREE days I was able to think clear and walk straight again.
I doubt that this information will be of much use for anyone who smokes weed/hash since I think it would be impossible to get as much THC in your body like I had that way. But a word of warning to the people that are experimenting with consuming weed/hash or extracting pure THC (honey oil and the likes): you should take into consideration that it can be unexpected strong. Really start with a low dosage since you can't compare it with smoking weed/hash and it can take you on surprise easily. Especially since you don't expect it from something as mild as weed.
Experience Reports are the writings and opinions of the individual authors who submit them.
Some of the activities described are dangerous and/or illegal and none are recommended by Erowid.


Adaptability Equals Longevity
Nothing is nature stands still. Why do we insist we do? Adaptability is the ability to change, without it we are just living in our past. Our past is a has-been, memories to be reflected on, lessons to be built upon, but not a place to reside. Change is the vehicle of evolution. It is the […]
by Charisse GlennNothing is nature stands still. Why do we insist we do?
Adaptability is the ability to change, without it we are just living in our past. Our past is a has-been, memories to be reflected on, lessons to be built upon, but not a place to reside.
Change is the vehicle of evolution. It is the guide to the future, the direction to flow. It is a function of life, as is evidenced in nature.
Nature has an innate understanding of adaptability, which is instrumental to longevity.
She is in harmony with the seasons. Everything has its time progressing fluidly through the process of discard and renewal. Animals grow or shed their fur, plants sprout, grow, flower then go dormant, while all along the moon travels through its phases, from full to a sliver and back again. The cycles create a framework in which all adapt.
Humans are masters at holding on to what was, keeping us trapped in a world that no longer exists. Innately many resist change, with an unfounded ferocity, even when we know it is for our best good.
And yet, we are willing to adjust to the latest technology waiting in line for hours to get the new iPhone, or for the newest automobile with the most up to date gadgets, even though the one we have is only a few years old.
Why are we so eager to adapt to meaningless external circumstances, but are inflexible to internal changes? We misplace our identity when we think the newest technology is a part of who we are.
The current headlines of Keanu Reeves and his new paramour have ruffled my feathers. The example may be a stretch to make my point, but the lack of willingness to accept what is out of the norm astounds me.
 Period. The fact she is a civilian, not a celebrity and has allowed her hair to follow the course of nature, good for her! What outrages me most are the articles about how she has singlehandedly given 40-year-olds the permission and courage to age! What the heck?
Why are we so easily manipulated by media and yet so reticent to make a change within ourselves unless we have the social acceptance first? We are quick to judge, to offer our unasked for opinions, yet the idea of altering our way of thinking can be stifling for many.
Perhaps there is a deep knowing that if we change our way of thinking, our lives will change, and we are fearful of the unknown.
But fear always lurks over us, and if fear is preventing us from moving forward, it is best addressed by FDR.
The only thing to fear is fear itself. Franklin D Roosevelt
To adapt is vital to forward-thinking and more importantly to longevity. Mother earth is the queen of adaptability. In spite of the devastation we are imposing on our habitat, it is only causing our demise. We can change her geology, disrupt her composition, burn her forests and melt the icecaps, but she will continue to adapt to whatever is thrown at her.
Long after she sluffs off the human race, she will continue to flourish. The landscape and topography may be altered, the climate will change and the species able to live here will have adjusted. Still, through her ability to adapt, she will survive the destruction humankind has forced upon her, just as she has survived the ice age and dinosaurs.
To let go of the rigidity of our thought, our unaltering cockiness and our disdain for those who step outside of societal norms is a good place to start.
The evolution of our thought will determine how we coexist with nature and how we excel in our personal quests for self-actualization.
Let us take our cue from mother earth’s wisdom. She is the essence of adaptability. Adaptability Equals Longevity.
Life must be lived as it is, and you cannot live at all, if you do not adapt yourself to your life as it happens to be.
~ Eleanor Roosevelt
— Published on November 15, 2019