About CaminteJS
CaminteJS is cross-db ORM for nodejs, providing common interface to access
most popular database formats.
CaminteJS adapters:
mongoose, mysql, sqlite3, riak, postgres, couchdb, mongodb, redis, neo4j, firebird, nano
Installation
First install node.js. Then:
$ npm install caminte -g
Overview
Connecting to DB
First, we need to define a connection.
MySQL
For MySQL database need install mysql client. Then:
$ npm install mysql -g
var caminte = require('caminte'),
Schema = caminte.Schema,
db = {
driver : "mysql",
host : "localhost",
port : "3306",
username : "test",
password : "test",
database : "test"
};
var schema = new Schema(db.driver, db);
Redis
For Redis database need install redis client. Then:
$ npm install redis -g
var caminte = require('caminte'),
Schema = caminte.Schema,
db = {
driver : "redis",
host : "localhost",
port : "6379"
};
var schema = new Schema(db.driver, db);
SQLite
For SQLite database need install sqlite3 client. Then:
$ npm install sqlite3 -g
var caminte = require('caminte'),
Schema = caminte.Schema,
db = {
driver : "sqlite3",
database : "/db/mySite.db"
};
var schema = new Schema(db.driver, db);
Defining a Model
Models are defined through the Schema
interface.
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, index: true }
});
var User = schema.define('User', {
name: String,
bio: Schema.Text,
approved: Boolean,
joinedAt: Date,
age: Number
});
Accessing a Model
schema.models.User;
schema.models.Post;
Setup Relationships
User.hasMany(Post, {as: 'posts', foreignKey: 'userId'});
Post.belongsTo(User, {as: 'author', foreignKey: 'userId'});
var user = new User;
user.save(function (err) {
var post = user.posts.build({title: 'Hello world'});
post.save(console.log);
});
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
}
})
Common API methods
Just instantiate model
var post = new Post();
#create(callback)
Save model (of course async)
Post.create(function(err){
});
user.posts.build
});
user.posts.create(function(err){
});
#all(params, callback)
Get all instances
var Query = Post.all();
Query.where('published', true).desc('date');
Query.run({}, function(err, post){
});
Post.all(function(err, posts){
});
Post.all({where: {userId: 2}, order: 'id', limit: 10, skip: 20}, function(err, posts){
});
user.posts(function(err, posts){
})
#find(params, callback)
Find instances
Post.find(function(err, posts){
});
var Query = Post.find();
Query.where('userId', 2);
Query.order('id', 'ASC');
Query.skip(20).limit(10);
Query.run({},function(err, posts){
});
Post.find({where: {userId: user.id}, order: 'id', limit: 10, skip: 20}, function(err, posts){
});
#findOrCreate(params, callback)
Find if exists or create instance
Post.findOrCreate({
where: {
title: 'First post'
}
}, function(err, post){
});
#findOne(params, callback)
Get one latest instance
{where: {published: true}, order: 'date DESC'}
Post.findOne({where: {published: true}, order: 'date DESC'}, function(err, post){
});
var Query = Post.findOne();
Query.where('published',true).desc('date');
Query.run({}, function(err, post){
});
#findById(id, callback)
Find instance by id
User.findById(1, function(err, post){
})
#updateOrCreate(params, callback)
Update if exists or create instance
Post.updateOrCreate({
where: {
userId: 100,
title: 'Riga'
}
}, function(err, post){
});
#count(params, callback)
Count instances
Post.count({where: {userId: user.id}}, function(err, count){
});
#remove(params, callback)
Remove instances
Post.remove({where: {published: false}},function(err){
});
#destroy(callback)
Destroy instance
user.destroy(function(err){
});
#destroyAll(callback)
Destroy all instances
User.destroyAll(function(err){
});
Define any Custom Method
User.prototype.getNameAndAge = function () {
return this.name + ', ' + this.age;
};
Queries
API methods
Example Queries
var Query = User.find();
Query.where('active', 1);
Query.order('id DESC');
Query.run({}, function(err, users) {
});
#where(key, val)
var Query = User.find();
Query.where('userId', user.id);
Query.run({}, function(err, count){
});
User.find({where: {userId: user.id}}, function(err, users){
});
#gt(key, val)
Specifies a greater than expression.
Query.gt('userId', 100);
Query.where('userId').gt(100);
User.find({
where: {
userId: {
gt : 100
}
}
}}, function(err, users){
});
#gte(key, val)
Specifies a greater than or equal to expression.
Query.gte('userId', 100);
Query.where('userId').gte(100);
User.find({
where: {
userId: {
gte : 100
}
}
}}, function(err, users){
});
#lt(key, val)
Specifies a less than expression.
Query.lt('visits', 100);
Query.where('visits').lt(100);
Post.find({
where: {
visits: {
lt : 100
}
}
}}, function(err, posts){
});
#lte(key, val)
Specifies a less than or equal to expression.
Query.lte('visits', 100);
Query.where('visits').lte(100);
Post.find({
where: {
visits: {
lte : 100
}
}
}}, function(err, posts){
});
#ne(key, val)
Matches all values that are not equal to the value specified in the query.
Query.ne('userId', 100);
Query.where('userId').ne(100);
User.find({
where: {
userId: {
ne : 100
}
}
}}, function(err, users){
});
#in(key, val)
Matches any of the values that exist in an array specified in the query.
Query.in('userId', [1,5,7,9]);
Query.where('userId').in([1,5,7,9]);
User.find({
where: {
userId: {
in : [1,5,7,9]
}
}
}}, function(err, users){
});
#regex(key, val)
Selects rows where values match a specified regular expression.
Query.regex('title', 'intel');
Query.where('title').regex('intel');
Post.find({
where: {
title: {
regex : 'intel'
}
}
}}, function(err, posts){
});
#like(key, val)
Pattern matching using a simple regular expression comparison.
Query.like('title', 'intel');
Post.find({
where: {
title: {
like : 'intel'
}
}
}}, function(err, posts){
});
#regex(key, val)
Pattern not matching using a simple regular expression comparison.
Query.nlike('title', 'intel');
Post.find({
where: {
title: {
nlike : 'intel'
}
}
}}, function(err, posts){
});
#nin(key, val)
Matches values that do not exist in an array specified to the query.
Query.nin('id', [1,2,3]);
Post.find({
where: {
title : {
nin : [1,2,3]
}
}
}}, function(err, posts){
});
#sort(key, val)
Sets the sort column and direction.
Query.sort('title DESC');
Query.sort('title', 'DESC');
Post.find({
order: 'title DESC'
}}, function(err, posts){
});
#asc(key)
Sets the sort column and direction ASC.
Query.asc('title');
Query.sort('title ASC');
Post.find({
order: 'title ASC'
}}, function(err, posts){
});
#desc(key)
Sets the sort column and direction DESC.
Query.desc('title');
Query.sort('title DESC');
Post.find({
order: 'title DESC'
}}, function(err, posts){
});
#skip(val)
The skip method specifies at which row the database should begin returning results.
Query.skip(10);
Post.find({
skip: 10
}}, function(err, posts){
});
#limit(val)
The limit method specifies the max number of rows to return.
Query.limit(10);
Post.find({
limit: 10
}}, function(err, posts){
});
#range(key, from, to)
The limit method specifies the max number of rows to return.
Query.range('id', 100, 200);
Post.find({
where: {
id: {
gt : 100.
lt : 200
}
}
}}, function(err, posts){
});
Middleware (callbacks)
The following callbacks supported:
- afterInitialize
- beforeCreate
- afterCreate
- beforeSave
- afterSave
- beforeUpdate
- afterUpdate
- beforeDestroy
- afterDestroy
- beforeValidation
- afterValidation
User.afterUpdate = function (next) {
this.updated_ts = new Date();
this.save();
next();
};
Each callback is class method of the model, it should accept single argument: next
, this is callback which
should be called after end of the hook. Except afterInitialize
because this method is syncronous (called after new Model
).
Automigrate
required only for mysql NOTE: it will drop User and Post tables
schema.automigrate();
Object lifecycle:
var user = new User;
user.save(callback);
user.updateAttribute('email', 'email@example.com', callback);
user.destroy(callback);
User.create(data, callback);
Read the tests for usage examples: ./test/common_test.js
Validations: ./test/validations_test.js
Your own database adapter
To use custom adapter, pass it's package name as first argument to Schema
constructor:
mySchema = new Schema('couch-db-adapter', {host:.., port:...});
Make sure, your adapter can be required (just put it into ./node_modules):
require('couch-db-adapter');
Running tests
To run all tests (requires all databases):
npm test
If you run this line, of course it will fall, because it requres different databases to be up and running,
but you can use js-memory-engine out of box! Specify ONLY env var:
ONLY=memory nodeunit test/common_test.js
of course, if you have redis running, you can run
ONLY=redis nodeunit test/common_test.js
Package structure
Now all common logic described in ./lib/*.js
, and database-specific stuff in ./lib/adapters/*.js
. It's super-tiny, right?
Contributing
If you have found a bug please write unit test, and make sure all other tests still pass before pushing code to repo.
Recommend extensions
License
(The MIT License)
Copyright (c) 2011 by Anatoliy Chakkaev <mail [åt] anatoliy [døt] in>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Resources