model.js
model.js is a simple ORM (Object Relational Mapper) for use with Node.js and MySQL.
Requirements
Usage
Define models
Create a model object by using the model()
function. It takes the following arguments:
- tableName - The name of the database table
- fields - A list of field names not including
id
It is assumed all tables have a primary key named id
of type INT with auto increment.
var User = ;
Connect to the database
Use the mysql
module to connect to the database.
var mysql = ;var db = mysql;db;
Save a row
Use the save()
function to save a row into the table. If the row has not been saved before, it will be assigned an id
automatically.
var john = db name: 'John' email: 'john@example.com';john;
Retrieve a row
Use the get()
function to retrieve a row from the table. Currently you can only retrieve rows by their id
.
var user_id = 1;var theUser = db id: user_id;theUser;
Access row data
Convert a row into an object literal using the data()
function.
var userData = theUserdata; // {id: 1, name: 'John', email: 'john@example.com'}
Update a row
Use the setData()
function to update a row's data.
theUser;theUser;
Or use a field's property to update a single field.
theUsername = 'Michael';theUser;
Remove a row
Use the remove()
function to delete a row from a table.
var theUser = db id: 1;theUser;
Count rows
Use the count()
function to count rows in a table by any equality condition.
User;
Define relationships
Define the relationship between model objects using the model.oneToMany()
function. It takes the following arguments:
parentModel
- The 'One' in the relationshipchildModel
- The 'Many' in the relationshipparentName
- The method name to access the parent from a childchildrenName
- The method name to access the list of children from the parentchildModelField
(optional) - The field name in the child corresponding to the parent id. If not specified, it is assumed to beparentName
+_id
var User = ;var Post = ;model; // childModelField becomes user_id
Currently One To Many relationships are the only type of relationship implemented in model.js.
Save related rows
var john = db id: 1;john;
Retrieve related rows
Get all of a user's posts:
var john = db id: 1;john;
Or get the user of a post:
var post = db id: 1;post;