I am building a little Node app and since I want to use OrientDB I cannot use Mongoose or the like for handling my data / models. So I have to come up with something on my own and I find it quite hard since I'm not that well vetted in Node.js (yet).
I am using oriento as my driver for OrientDB. Oriento's API is based on bluebird promises.
This is how far I got. But I am pretty sure there must be a better way to handle errors (like 'record not found').
Any hints on how to improve this are welcome. Maybe there even is a package for creating models that aren't tied to a specific database that I haven't found yet.
./utils/oriento.js
// instantiate it once and share in multiple places(models), since it offers
// connection pooling
// Connect to Database
var Oriento = require('oriento');
var orientserver = Oriento({
host: 'localhost',
port: 2424,
username: 'root',
password: 'password'
});
var db = orientserver.use({
name: 'database',
username: 'root',
password: 'password'
});
console.log('Using database: ' + db.name);
module.exports = db;
./models/user.js
var db = require('../utils/oriento.js');
var User = function (data) {
this.data = {
username: data.username,
email: data.email
};
}
User.prototype.data = {}
User.findByUsername = function(username, callback){
db.select().from('users').where({username: username}).one()
.then(function (user) {
if (user === undefined) {
return callback(false);
} else {
callback(new User(user));
}
});
}
// add getters, setters, find etc...
module.exports = User;
./app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// Models
// I KNOW this doesn't belong here.
// I just put it here for quick testing before writing any controllers
User = require("./models/user.js");
User.findByUsername('ole', function (user) {
if(user) {
console.log("my object: ", user);
} else {
console.log("Nothing found");
}
});
// etc...