您的位置:首页 > Web前端 > Node.js

Node.js ORM框架:ORM2

2015-07-14 15:33 543 查看
项目地址: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, // FLOAT5. male : Boolean,6. continent : [ "Europe", "America", "Asia", "Africa", "Australia", "Antartica" ], // ENUM type7. photo : Buffer, // BLOB/BINARY8. data : Object // JSON encoded9. }, {10. methods: {11. fullName: function () {12. return this.name + ' ' + this.surname;13. }14. },15. validations: {16. age: orm.enforce.ranges.number(18, undefined, "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. });
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: