Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database inheritance model with Node.js

Using Node.js and a SQL-like database, what are my options when it comes to implementing database inheritance model? I looked around and it seems that due to popularity of noSQL database in Node.js, database inheritance is overlooked.

I'm trying to accomplish a very simple thing: extend a Users table based on a few business rules. For simplicity, I'd want to add Reader and Moderator tables and classes whose properties would differ. This is something that would be relatively easy to accomplish in .NET using NHibernate. Can I achieve the same result without using sticking everything in the same table? If not, what are the best alternatives?

Btw, I'm using Node.js with PostreSQL via Sequelize.

like image 255
MK_Dev Avatar asked Oct 05 '12 03:10

MK_Dev


1 Answers

I have not seen an ORM for SQL databases that supports inheritance yet. Even then, I believe there are other opportunities thanks to the nature of JS that you might enjoy (I sure do):

Using jugglingdb (the one I would recommend), coupled with underscore.js (something most node.js programmers should pay attention to) you can do something like the following:

var user_common_properties = {
    name:         String,
    bio:          Schema.Text,
    approved:     Boolean,
    joinedAt:     Date,
    age:          Number
};
var User = schema.define('User', user_common_properties);

var Moderator = schema.define('Moderator', _.extend(user_common_properties, {
    power : String,
    level : Number
}));
var Reader = schema.define('Moderator', _.extend(user_common_properties, {
    lurker : Boolean
}));

While I agree it's not the same, there are no reasons to consider this bad :) I think it is very JavaScript-like.

Also, if you want to re-use methods/validations, you can! Just assign it to them (re-use the functions) or if you want to re-use a bunch of functions, add them to an object and then extend the Reader and Moderator objects. For example...

var repeated_methods = {
    first : function () { },
    second: function () {}
};
//I want to reuse this for both User and Moderator but not for Reader...
User = _.extend(User, repeated_methods);
Moderator = _.extend(Moderator, repeated_methods);

This is very flexible and allow for has-a relationships (behaviors), which is great for horizontal reuse.

like image 150
Mamsaac Avatar answered Sep 30 '22 13:09

Mamsaac