Sequelize is an ORM for Node.js that I have decided to use in a project. I, like most of my fellow programmers, generally like cleaner code and in this case I found a pretty damn good way to initialize it and keep the initializing functions separate from rest of the code. Further, I structured it so that it was very easy to use it as well.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
var db = { Notes: sequelize.define('Notes', { text: Sequelize.STRING, title: Sequelize.STRING, description: Sequelize.TEXT, width: Sequelize.FLOAT, height: Sequelize.FLOAT, offsetLeft: Sequelize.FLOAT, offsetTop: Sequelize.FLOAT, zIndex: Sequelize.INTEGER }), Boards: sequelize.define('Boards', { title: Sequelize.STRING, description: Sequelize.TEXT, created: Sequelize.DATE }), init: function(){ //init this bitch this.Boards.hasMany(this.Notes); this.Boards.sync(); this.Notes.sync(); } }; |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
//this is async, so save will fail initially. //ideally we would try to fire a callback instead of trying to do this synchronously. //But it demonstrates the idea, anyhow. db.init(); var board = db.Boards.build({ title: "title", description: "description", created: new Date() }); board.save(); |
This is how you use that, this is a bit complicated because it’s from an actual application:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
try{ var board = db.Boards.build({ path: _boardName, title: "title", description: "description", created: new Date() }); board.save(); }catch(error){ console.log(error.text); } |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
db.Boards.find({where: {path: _boardName}}).success(function(board){ //board.build(); board.getNotes().success( function(notes){ dbresults = new Array(); for(n=0; n < notes.length; n++){ //console.log(notes[0]); var fields = {}; for(i=0; i < notes[n].attributes.length; i++){ key = notes[n].attributes[i]; value = notes[n][key]; fields[key] = value; } dbresults.push(fields); } //res.send(dbresults); res.contentType('json'); //res.contentType('application/javascript'); callback = req.query.callback; res.send(callback + '(' + JSON.stringify(dbresults) + ');'); } ); }); |
Nice and well explained, but there is a way to demonstrate how to connect to a database and exchange some elements with it, ’cause I’m working on a project that need a communication to DB under node.js
I updated the existing entry with some more example code about how you might try using this.