登录
注册
node.js 学习社区
Node.js ORM框架:ORM2

龙三

2015-01-30 14:54

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

支持的数据库:

  • MySQL & MariaDB
  • PostgreSQL
  • Amazon Redshift
  • SQLite

安装

npm install orm

连接数据库

var orm = require("orm");

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

定义模型

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")
        }
    });

查找

Person.find({ surname: "Doe" }, function (err, people) {
        // SQL: "SELECT * FROM person WHERE surname = 'Doe'"

        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";
        });
});

删除和同步表

db.drop(function () {
        // 删除所有表

        Person.sync(function () {
            // 创建Person表
        });
    });

创建

var newRecord = {};
newRecord.id = 1;
newRecord.name = "John"
Person.create(newRecord, function(err, results) {
 ...
});

更新

Person.find({ surname: "Doe" }, function (err, people) {
        // SQL: "SELECT * FROM person WHERE surname = 'Doe'"

        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";
        });
    });
更多特性参考官方Wiki: https://github.com/dresende/node-orm2/wiki


回复 · 2

发表回复

你可以在回复中 @ 其他人