🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# orm2 中文文档 > 译者:[飞龙](https://github.com/wizardforcel) > 来源:[Object Relational Mapping](https://github.com/dresende/node-orm2/blob/master/Readme.md) ## 安装 ``` 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](https://travis-ci.org/) 上运行。如果你想要的话,可以在本地运行测试: ``` npm test ``` ## DBMS 支持 + MySQL & MariaDB + PostgreSQL + Amazon Redshift + SQLite + MongoDB (beta版,到现在为止缺少聚合) ## 特性 + 创建模型,同步,删除,批量创建,获取,查找,移除,计数,聚合函数 + 创建模型的关联,查找,检查,创建和移除 + 定义自定义的验证器(有一些内建的验证器,会在保存之前检查实例的属性 -- 详见[enforce](http://github.com/dresende/node-enforce) + 模型实例的缓存和一致性(两次获取表中的一行,获取到相同的对象,修改其中一个就是修改全部) + 插件:[MySQL FTS](http://dresende.github.io/node-orm-mysql-fts),[Pagination](http://dresende.github.io/node-orm-paging) (分页),[Transaction](http://dresende.github.io/node-orm-transaction) (事务),[Timestamps](http://github.com/SPARTAN563/node-orm-timestamps) (时间戳),[Migrations](https://github.com/locomote/node-migrate-orm2) (迁移) ## 介绍 这是一个 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的包装库](https://github.com/rafaelkaufmann/q-orm)。 ## 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`](https://github.com/dresende/node-orm2/tree/master/examples/anontxt),里面有一个基于express的应用示例。