Node.js ORM框架:bookshelf

cw63 8年前

一个基于Knex.js的Node.js ORM框架,支持PostgreSQL,MySQL和SQLite3

简单来说,Bookself是一个优秀的代码库,它易于阅读、理解、可扩展。它不强制你使用任何特定的校验scheme,而是提供灵活有效的关系或嵌套关系加载策略,一级类支持事务。它是一个精益的对象关系映射器(lean Object Relation Mapper),允许你使用原始的knex接口,当你需要自定义查询时,因为它有时并不能完全满足老一套的惯例。

Bookshelf遵从和Backbone.js一样棒的Models和Collections思想,使用相同的模式、命名惯例和哲学构建轻量、易于操控的ORM。如果你已经了解Backbone,你就知道如何使用Bookshelf.

插件

  • Registry: Register models in a central location so that you can refer to them using a string in relations instead of having to require it every time. Helps deal with the challenges of circular module dependencies in Node.
  • Virtuals: Define virtual properties on your model to compute new values.
  • Visibility: Specify a whitelist/blacklist of model attributes when serialized toJSON.

支持

Have questions about the library? Come join us in the #bookshelf freenode IRC channel for support on knex.js and bookshelf.js, or post an issue on Stack Overflow or in the GitHub issue tracker.

示例:

var knex = require('knex')({client: 'mysql', connection: process.env.MYSQL_DATABASE_CONNECTION });  var bookshelf = require('bookshelf')(knex);  var User = bookshelf.Model.extend({    tableName: 'users',    messages: function() {      return this.hasMany(Posts);    }  });  var Posts = bookshelf.Model.extend({    tableName: 'messages',    tags: function() {      return this.belongsToMany(Tag);    }  });  var Tag = bookshelf.Model.extend({    tableName: 'tags'  })  User.where('id', 1).fetch({withRelated: ['posts.tags']}).then(function(user) {    console.log(user.related('posts').toJSON());  }).catch(function(err) {    console.error(err);  });

项目主页:http://www.open-open.com/lib/view/home/1443236568201