译者:飞龙
安装
npm install orm所支持的Node.js版本
支持 0.8, 0.10, 0.12, iojs-1.5 。
0.10.x,0.12.x 和 iojs-1.5 版本的测试在 Travis CI 上运行。如果你想要的话,可以在本地运行测试:
npm testDBMS 支持
- MySQL & MariaDB
 - PostgreSQL
 - Amazon Redshift
 - SQLite
 - MongoDB (beta版,到现在为止缺少聚合)
 
特性
- 创建模型,同步,删除,批量创建,获取,查找,移除,计数,聚合函数
 - 创建模型的关联,查找,检查,创建和移除
 - 定义自定义的验证器(有一些内建的验证器,会在保存之前检查实例的属性 – 详见enforce
 - 模型实例的缓存和一致性(两次获取表中的一行,获取到相同的对象,修改其中一个就是修改全部)
 - 插件:MySQL FTS,Pagination (分页),Transaction (事务),Timestamps (时间戳),Migrations (迁移)
 
介绍
这是一个 Node.js 对象关系映射模块。
示例:
var orm = require("orm");
orm.connect("mysql://username:password@host/database", function (err, db) {
  if (err) throw err;
    var Person = db.define("person", {
        name      : String,
        surname   : String,
        age       : Number, // FLOAT
        male      : Boolean,
        continent : [ "Europe", "America", "Asia", "Africa", "Australia", "Antartica" ], // ENUM type
        photo     : Buffer, // BLOB/BINARY
        data      : Object // JSON encoded
    }, {
        methods: {
            fullName: function () {
                return this.name + ' ' + this.surname;
            }
        },
        validations: {
            age: orm.enforce.ranges.number(18, undefined, "under-age")
        }
    });
    // add the table to the database
    db.sync(function(err) { 
        if (err) throw err;
        // add a row to the person table
        Person.create({ id: 1, name: "John", surname: "Doe", age: 27 }, function(err) {
            if (err) throw err;
                // query the person table by surname
                Person.find({ surname: "Doe" }, function (err, people) {
                    // SQL: "SELECT * FROM person WHERE surname = 'Doe'"
                    if (err) throw err;
                    console.log("People found: %d", people.length);
                    console.log("First person: %s, age %d", people[0].fullName(), people[0].age);
                    people[0].age = 16;
                    people[0].save(function (err) {
                        // err.msg = "under-age";
                });
            });
        });
    });
});Promise
你可以使用开启Promise的包装库。
Express
如果你使用了Express,你可能想使用这一简单的中间件,使集成变得更容易。
var express = require('express');
var orm = require('orm');
var app = express();
app.use(orm.express("mysql://username:password@host/database", {
    define: function (db, models, next) {
        models.person = db.define("person", { ... });
        next();
    }
}));
app.listen(80);
app.get("/", function (req, res) {
    // req.models is a reference to models used above in define()
    req.models.person.find(...);
});你可以多次调用orm.express来获取多个数据库的连接。在多个连接之间定义的模型会在req.models中连接。不要忘记在app.use(app.router)之前使用它,最好在你的公共素材文件夹之后。
示例
请见examples/anontxt,里面有一个基于express的应用示例。
                










