项目地址:https://github.com/dresende/node-orm2

支持的数据库:

· MySQL & MariaDB

· PostgreSQL

· Amazon Redshift

· SQLite

安装

1. npm install orm

连接数据库

1. var orm = require("orm");

2. 

3. orm.connect("mysql://username:password@host/database"function (err, db) {

4. //...

5. });

定义模型

1. var Person = db.define("person", {

2.         name      : String,

3.         surname   : String,

4.         age       : Number// FLOAT

5.         male      : Boolean,

6.         continent : [ "Europe""America""Asia""Africa""Australia""Antartica" ], // ENUM type

7.         photo     : Buffer// BLOB/BINARY

8.         data      : Object // JSON encoded

9.     }, {

10.         methods: {

11.             fullName: function () {

12.                 return this.name + ' ' + this.surname;

13.             }

14.         },

15.         validations: {

16.             age: orm.enforce.ranges.number(18undefined"under-age")

17.         }

18.     });

查找

1. Person.find({ surname: "Doe" }, function (err, people) {

2.         // SQL: "SELECT * FROM person WHERE surname = 'Doe'"

3. 

4.         console.log("People found: %d", people.length);

5.         console.log("First person: %s, age %d", people[0].fullName(), people[0].age);

6. 

7.         people[0].age = 16;

8.         people[0].save(function (err) {

9.             // err.msg = "under-age";

10.         });

11. });

删除和同步表

1. db.drop(function () {

2.         // 删除所有表

3. 

4.         Person.sync(function () {

5.             // 创建Person表

6.         });

7.     });

创建

1. var newRecord = {};

2. newRecord.id = 1;

3. newRecord.name = "John"

4. Person.create(newRecord, function(err, results) {

5.  ...

6. });

更新

1. Person.find({ surname: "Doe" }, function (err, people) {

2.         // SQL: "SELECT * FROM person WHERE surname = 'Doe'"

3. 

4.         console.log("People found: %d", people.length);

5.         console.log("First person: %s, age %d", people[0].fullName(), people[0].age);

6. 

7.         people[0].age = 16;

8.         people[0].save(function (err) {

9.             // err.msg = "under-age";

10.         });

11.     });