JugglingDB - 支持多种数据库的ORM框架
JugglingDB是一个支持多种数据库的ORM框架,它为当前流行的数据库提供通用访问接口。支持的数据库包括:mysql, mongodb, redis, neo4j 和 js-memory-storage。你可以添加你自己数据库的适配器adapter,可以参考现有adapter的写法,超级简单。用法:
var Schema = require('./jugglingdb').Schema; var schema = new Schema('redis', {port: 6379}); //port number depends on your configuration // define models var Post = schema.define('Post', { title: { type: String, length: 255 }, content: { type: Schema.Text }, date: { type: Date, default: Date.now }, published: { type: Boolean, default: false } }); // simplier way to describe model var User = schema.define('User', { name: String, bio: Schema.Text, approved: Boolean, joinedAt: Date, age: Number }); // setup relationships User.hasMany(Post, {as: 'posts', foreignKey: 'userId'}); // creates instance methods: // user.posts(conds) // user.posts.build(data) // like new Post({userId: user.id}); // user.posts.create(data) // build and save Post.belongsTo(User, {as: 'author', foreignKey: 'userId'}); // creates instance methods: // post.author(callback) -- getter when called with function // post.author() -- sync getter when called without params // post.author(user) -- setter when called with object schema.automigrate(); // required only for mysql NOTE: it will drop User and Post tables // work with models: var user = new User; user.save(function (err) { var post = user.posts.build({title: 'Hello world'}); post.save(console.log); }); // or just call it as function (with the same result): var user = User(); user.save(...); // Common API methods // just instantiate model new Post // save model (of course async) Post.create(cb); // all posts Post.all(cb) // all posts by user Post.all({where: {userId: user.id}, order: 'id', limit: 10, skip: 20}); // the same as prev user.posts(cb) // same as new Post({userId: user.id}); user.posts.build // save as Post.create({userId: user.id}, cb); user.posts.create(cb) // find instance by id User.find(1, cb) // count instances User.count([conditions, ]cb) // destroy instance user.destroy(cb); // destroy all instances User.destroyAll(cb); // Setup validations User.validatesPresenceOf('name', 'email') User.validatesLengthOf('password', {min: 5, message: {min: 'Password is too short'}}); User.validatesInclusionOf('gender', {in: ['male', 'female']}); User.validatesExclusionOf('domain', {in: ['www', 'billing', 'admin']}); User.validatesNumericalityOf('age', {int: true}); User.validatesUniquenessOf('email', {message: 'email is not unique'}); user.isValid(function (valid) { if (!valid) { user.errors // hash of errors {attr: [errmessage, errmessage, ...], attr: ...} }
本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!