Object Relational Mapping

Overview

Object Relational Mapping

Build Status FOSSA Status Flattr this git repo

This package is not actively maintained

If you're starting a new project, please consider using one of the following instead as they have a much more active community:

Install

npm install orm

Node.js Version Support

Supported: 4.0 +

Tests are run on Travis CI If you want you can run tests locally:

npm test

DBMS Support

  • MySQL & MariaDB
  • PostgreSQL
  • Amazon Redshift
  • SQLite
  • MongoDB (beta, node 6 or older, doesn't work with node 8. Also, missing aggregation features)

Features

  • Create Models, sync, drop, bulk create, get, find, remove, count, aggregated functions
  • Create Model associations, find, check, create and remove
  • Define custom validations (several builtin validations, check instance properties before saving - see enforce for details)
  • Model instance caching and integrity (table rows fetched twice are the same object, changes to one change all)
  • Plugins: MySQL FTS , Pagination , Transaction, Timestamps, Migrations

Introduction

This is a node.js object relational mapping module.

An example:

var orm = require("orm");

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

  var Person = db.define("person", {
    name      : String,
    surname   : String,
    age       : Number, // FLOAT
    male      : Boolean,
    continent : [ "Europe", "America", "Asia", "Africa", "Australia", "Antarctica" ], // 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")
    }
  });

  // add the table to the database
  db.sync(function(err) {
    if (err) throw err;

    // add a row to the person table
    Person.create({ id: 1, name: "John", surname: "Doe", age: 27 }, function(err) {
      if (err) throw err;

      // query the person table by surname
      Person.find({ surname: "Doe" }, function (err, people) {
        // SQL: "SELECT * FROM person WHERE surname = 'Doe'"
        if (err) throw err;

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

Express

If you're using Express, you might want to use the simple middleware to integrate more easily.

var express = require('express');
var orm = require('orm');
var app = express();

app.use(orm.express("mysql://username:password@host/database", {
	define: function (db, models, next) {
		models.person = db.define("person", { ... });
		next();
	}
}));
app.listen(80);

app.get("/", function (req, res) {
	// req.models is a reference to models used above in define()
	req.models.person.find(...);
});

You can call orm.express more than once to have multiple database connections. Models defined across connections will be joined together in req.models. Don't forget to use it before app.use(app.router), preferably right after your assets public folder(s).

Examples

See examples/anontxt for an example express based app.

Documentation

Documentation is moving to the wiki.

Settings

See information in the wiki.

Connecting

See information in the wiki.

Models

A Model is an abstraction over one or more database tables. Models support associations (more below). The name of the model is assumed to match the table name.

Models support behaviours for accessing and manipulating table data.

Defining Models

See information in the wiki.

Properties

See information in the wiki.

Instance Methods

Are passed in during model definition.

var Person = db.define('person', {
    name    : String,
    surname : String
}, {
    methods: {
        fullName: function () {
            return this.name + ' ' + this.surname;
        }
    }
});

Person.get(4, function(err, person) {
    console.log( person.fullName() );
})

Model Methods

Are defined directly on the model.

var Person = db.define('person', {
    name    : String,
    height  : { type: 'integer' }
});
Person.tallerThan = function(height, callback) {
    this.find({ height: orm.gt(height) }, callback);
};

Person.tallerThan( 192, function(err, tallPeople) { ... } );

Loading Models

Models can be in separate modules. Simply ensure that the module holding the models uses module.exports to publish a function that accepts the database connection, then load your models however you like.

Note - using this technique you can have cascading loads.

// your main file (after connecting)
db.load("./models", function (err) {
  // loaded!
  var Person = db.models.person;
  var Pet    = db.models.pet;
});

// models.js
module.exports = function (db, cb) {
  db.load("./models-extra", function (err) {
    if (err) {
      return cb(err);
    }

    db.define('person', {
      name : String
    });

    return cb();
  });
};

// models-extra.js
module.exports = function (db, cb) {
  db.define('pet', {
      name : String
  });

  return cb();
};

Synchronizing Models

See information in the wiki.

Dropping Models

See information in the wiki.

Advanced Options

ORM2 allows you some advanced tweaks on your Model definitions. You can configure these via settings or in the call to define when you setup the Model.

For example, each Model instance has a unique ID in the database. This table column is added automatically, and called "id" by default.
If you define your own key: true column, "id" will not be added:

var Person = db.define("person", {
	personId : { type: 'serial', key: true },
	name     : String
});

// You can also change the default "id" property name globally:
db.settings.set("properties.primary_key", "UID");

// ..and then define your Models
var Pet = db.define("pet", {
	name : String
});

Pet model will have 2 columns, an UID and a name.

It's also possible to have composite keys:

var Person = db.define("person", {
	firstname : { type: 'text', key: true },
	lastname  : { type: 'text', key: true }
});

Other options:

  • identityCache : (default: false) Set it to true to enable identity cache (Singletons) or set a timeout value (in seconds);
  • autoSave : (default: false) Set it to true to save an Instance right after changing any property;
  • autoFetch : (default: false) Set it to true to fetch associations when fetching an instance from the database;
  • autoFetchLimit : (default: 1) If autoFetch is enabled this defines how many hoops (associations of associations) you want it to automatically fetch.

Hooks

See information in the wiki.

Finding Items

Model.get(id, [ options ], cb)

To get a specific element from the database use Model.get.

Person.get(123, function (err, person) {
	// finds person with id = 123
});

Model.find([ conditions ] [, options ] [, limit ] [, order ] [, cb ])

Finding one or more elements has more options, each one can be given in no specific parameter order. Only options has to be after conditions (even if it's an empty object).

Person.find({ name: "John", surname: "Doe" }, 3, function (err, people) {
	// finds people with name='John' AND surname='Doe' and returns the first 3
});

If you need to sort the results because you're limiting or just because you want them sorted do:

Person.find({ surname: "Doe" }, "name", function (err, people) {
	// finds people with surname='Doe' and returns sorted by name ascending
});
Person.find({ surname: "Doe" }, [ "name", "Z" ], function (err, people) {
	// finds people with surname='Doe' and returns sorted by name descending
	// ('Z' means DESC; 'A' means ASC - default)
});

There are more options that you can pass to find something. These options are passed in a second object:

Person.find({ surname: "Doe" }, { offset: 2 }, function (err, people) {
	// finds people with surname='Doe', skips the first 2 and returns the others
});

You can also use raw SQL when searching. It's documented in the Chaining section below.

Model.count([ conditions, ] cb)

If you just want to count the number of items that match a condition you can just use .count() instead of finding all of them and counting. This will actually tell the database server to do a count (it won't be done in the node process itself).

Person.count({ surname: "Doe" }, function (err, count) {
	console.log("We have %d Does in our db", count);
});

Model.exists([ conditions, ] cb)

Similar to .count(), this method just checks if the count is greater than zero or not.

Person.exists({ surname: "Doe" }, function (err, exists) {
	console.log("We %s Does in our db", exists ? "have" : "don't have");
});

Aggregating Functions

If you need to get some aggregated values from a Model, you can use Model.aggregate(). Here's an example to better illustrate:

Person.aggregate({ surname: "Doe" }).min("age").max("age").get(function (err, min, max) {
	console.log("The youngest Doe guy has %d years, while the oldest is %d", min, max);
});

An Array of properties can be passed to select only a few properties. An Object is also accepted to define conditions.

Here's an example to illustrate how to use .groupBy():

//The same as "select avg(weight), age from person where country='someCountry' group by age;"
Person.aggregate(["age"], { country: "someCountry" }).avg("weight").groupBy("age").get(function (err, stats) {
  // stats is an Array, each item should have 'age' and 'avg_weight'
});

Base .aggregate() methods

  • .limit(): you can pass a number as a limit, or two numbers as offset and limit respectively
  • .order(): same as Model.find().order()

Additional .aggregate() methods

  • min
  • max
  • avg
  • sum
  • count (there's a shortcut to this - Model.count)

There are more aggregate functions depending on the driver (Math functions for example).

Chaining

If you prefer less complicated syntax you can chain .find() by not giving a callback parameter.

Person.find({ surname: "Doe" }).limit(3).offset(2).only("name", "surname").run(function (err, people) {
    // finds people with surname='Doe', skips first 2 and limits to 3 elements,
    // returning only 'name' and 'surname' properties
});

If you want to skip just one or two properties, you can call .omit() instead of .only.

Chaining allows for more complicated queries. For example, we can search by specifying custom SQL:

Person.find({ age: 18 }).where("LOWER(surname) LIKE ?", ['dea%']).all( ... );

It's bad practice to manually escape SQL parameters as it's error prone and exposes your application to SQL injection. The ? syntax takes care of escaping for you, by safely substituting the question mark in the query with the parameters provided. You can also chain multiple where clauses as needed.

.find, .where & .all do the same thing; they are all interchangeable and chainable.

You can also order or orderRaw:

Person.find({ age: 18 }).order('-name').all( ... );
// see the 'Raw queries' section below for more details
Person.find({ age: 18 }).orderRaw("?? DESC", ['age']).all( ... );

You can also chain and just get the count in the end. In this case, offset, limit and order are ignored.

Person.find({ surname: "Doe" }).count(function (err, people) {
  // people = number of people with surname="Doe"
});

Also available is the option to remove the selected items. Note that a chained remove will not run any hooks.

Person.find({ surname: "Doe" }).remove(function (err) {
  // Does gone..
});

You can also make modifications to your instances using common Array traversal methods and save everything in the end.

Person.find({ surname: "Doe" }).each(function (person) {
	person.surname = "Dean";
}).save(function (err) {
	// done!
});

Person.find({ surname: "Doe" }).each().filter(function (person) {
	return person.age >= 18;
}).sort(function (person1, person2) {
	return person1.age < person2.age;
}).get(function (people) {
	// get all people with at least 18 years, sorted by age
});

Of course you could do this directly on .find(), but for some more complicated tasks this can be very usefull.

Model.find() does not return an Array so you can't just chain directly. To start chaining you have to call .each() (with an optional callback if you want to traverse the list). You can then use the common functions .filter(), .sort() and .forEach() more than once.

In the end (or during the process..) you can call:

  • .count() if you just want to know how many items there are;
  • .get() to retrieve the list;
  • .save() to save all item changes.

Conditions

Conditions are defined as an object where every key is a property (table column). All keys are supposed to be concatenated by the logical AND. Values are considered to match exactly, unless you're passing an Array. In this case it is considered a list to compare the property with.

{ col1: 123, col2: "foo" } // `col1` = 123 AND `col2` = 'foo'
{ col1: [ 1, 3, 5 ] } // `col1` IN (1, 3, 5)

If you need other comparisons, you have to use a special object created by some helper functions. Here are a few examples to describe it:

{ col1: orm.eq(123) } // `col1` = 123 (default)
{ col1: orm.ne(123) } // `col1` <> 123
{ col1: orm.gt(123) } // `col1` > 123
{ col1: orm.gte(123) } // `col1` >= 123
{ col1: orm.lt(123) } // `col1` < 123
{ col1: orm.lte(123) } // `col1` <= 123
{ col1: orm.between(123, 456) } // `col1` BETWEEN 123 AND 456
{ col1: orm.not_between(123, 456) } // `col1` NOT BETWEEN 123 AND 456
{ col1: orm.like(12 + "%") } // `col1` LIKE '12%'
{ col1: orm.not_like(12 + "%") } // `col1` NOT LIKE '12%'
{ col1: orm.not_in([1, 4, 8]) } // `col1` NOT IN (1, 4, 8)

Raw queries

db.driver.execQuery("SELECT id, email FROM user", function (err, data) { ... })

// You can escape identifiers and values.
// For identifier substitution use: ??
// For value substitution use: ?
db.driver.execQuery(
  "SELECT user.??, user.?? FROM user WHERE user.?? LIKE ? AND user.?? > ?",
  ['id', 'name', 'name', 'john', 'id', 55],
  function (err, data) { ... }
)

// Identifiers don't need to be scaped most of the time
db.driver.execQuery(
  "SELECT user.id, user.name FROM user WHERE user.name LIKE ? AND user.id > ?",
  ['john', 55],
  function (err, data) { ... }
)

Identity pattern

You can use the identity pattern (turned off by default). If enabled, multiple different queries will result in the same result - you will get the same object. If you have other systems that can change your database or you need to call some manual SQL queries, you shouldn't use this feature. It is also know to cause some problems with complex autofetch relationships. Use at your own risk.

It can be enabled/disabled per model:

var Person = db.define('person', {
	name          : String
}, {
	identityCache : true
});

and also globally:

orm.connect('...', function(err, db) {
  db.settings.set('instance.identityCache', true);
});

The identity cache can be configured to expire after a period of time by passing in a number instead of a boolean. The number will be considered the cache timeout in seconds (you can use floating point).

Note: One exception about Caching is that it won't be used if an instance is not saved. For example, if you fetch a Person and then change it, while it doesn't get saved it won't be passed from Cache.

Creating Items

Model.create(items, cb)

To insert new elements to the database use Model.create.

Person.create([
	{
		name: "John",
		surname: "Doe",
		age: 25,
		male: true
	},
	{
		name: "Liza",
		surname: "Kollan",
		age: 19,
		male: false
	}
], function (err, items) {
	// err - description of the error or null
	// items - array of inserted items
});

Updating Items

Every item returned has the properties that were defined to the Model and also a couple of methods you can use to change each item.

Person.get(1, function (err, John) {
	John.name = "Joe";
	John.surname = "Doe";
	John.save(function (err) {
		console.log("saved!");
	});
});

Updating and then saving an instance can be done in a single call:

Person.get(1, function (err, John) {
	John.save({ name: "Joe", surname: "Doe" }, function (err) {
		console.log("saved!");
	});
});

If you want to remove an instance, just do:

// you could do this without even fetching it, look at Chaining section above
Person.get(1, function (err, John) {
	John.remove(function (err) {
		console.log("removed!");
	});
});

Validations

See information in the wiki.

Associations

An association is a relation between one or more tables.

hasOne

Is a many to one relationship. It's the same as belongs to.
Eg: Animal.hasOne('owner', Person).
Animal can only have one owner, but Person can have many animals.
Animal will have the owner_id property automatically added.

The following functions will become available:

animal.getOwner(function..)         // Gets owner
animal.setOwner(person, function..) // Sets owner_id
animal.hasOwner(function..)         // Checks if owner exists
animal.removeOwner()                // Sets owner_id to 0

Chain Find

The hasOne association is also chain find compatible. Using the example above, we can do this to access a new instance of a ChainFind object:

Animal.findByOwner({ /* options */ })

Reverse access

Animal.hasOne('owner', Person, {reverse: 'pets'})

will add the following:

// Instance methods
person.getPets(function..)
person.setPets(cat, function..)

// Model methods
Person.findByPets({ /* options */ }) // returns ChainFind object

hasMany

Is a many to many relationship (includes join table).
Eg: Patient.hasMany('doctors', Doctor, { why: String }, { reverse: 'patients', key: true }).
Patient can have many different doctors. Each doctor can have many different patients.

This will create a join table patient_doctors when you call Patient.sync():

column name type
patient_id Integer (composite key)
doctor_id Integer (composite key)
why varchar(255)

The following functions will be available:

patient.getDoctors(function..)           // List of doctors
patient.addDoctors(docs, function...)    // Adds entries to join table
patient.setDoctors(docs, function...)    // Removes existing entries in join table, adds new ones
patient.hasDoctors(docs, function...)    // Checks if patient is associated to specified doctors
patient.removeDoctors(docs, function...) // Removes specified doctors from join table

doctor.getPatients(function..)
etc...

// You can also do:
patient.doctors = [doc1, doc2];
patient.save(...)

To associate a doctor to a patient:

patient.addDoctor(surgeon, {why: "remove appendix"}, function(err) { ... } )

which will add {patient_id: 4, doctor_id: 6, why: "remove appendix"} to the join table.

getAccessor

This accessor in this type of association returns a ChainFind if not passing a callback. This means you can do things like:

patient.getDoctors().order("name").offset(1).run(function (err, doctors), {
	// ... all doctors, ordered by name, excluding first one
});

extendsTo

If you want to split maybe optional properties into different tables or collections. Every extension will be in a new table, where the unique identifier of each row is the main model instance id. For example:

var Person = db.define("person", {
    name : String
});
var PersonAddress = Person.extendsTo("address", {
    street : String,
    number : Number
});

This will create a table person with columns id and name. The extension will create a table person_address with columns person_id, street and number. The methods available in the Person model are similar to an hasOne association. In this example you would be able to call .getAddress(cb), .setAddress(Address, cb), ..

Note: you don't have to save the result from Person.extendsTo. It returns an extended model. You can use it to query directly this extended table (and even find the related model) but that's up to you. If you only want to access it using the original model you can just discard the return.

Examples & options

If you have a relation of 1 to n, you should use hasOne (belongs to) association.

var Person = db.define('person', {
  name : String
});
var Animal = db.define('animal', {
  name : String
});
Animal.hasOne("owner", Person); // creates column 'owner_id' in 'animal' table

// get animal with id = 123
Animal.get(123, function (err, animal) {
  // animal is the animal model instance, if found
  animal.getOwner(function (err, person) {
    // if animal has really an owner, person points to it
  });
});

You can mark the owner_id field as required in the database by specifying the required option:

Animal.hasOne("owner", Person, { required: true });

If a field is not required, but should be validated even if it is not present, then specify the alwaysValidate option. (this can happen, for example when validation of a null field depends on other fields in the record)

Animal.hasOne("owner", Person, { required: false, alwaysValidate: true });

If you prefer to use another name for the field (owner_id) you can change this parameter in the settings.

db.settings.set("properties.association_key", "{field}_{name}"); // {name} will be replaced by 'owner' and {field} will be replaced by 'id' in this case

Note: This has to be done before the association is specified.

The hasMany associations can have additional properties in the association table.

var Person = db.define('person', {
    name : String
});
Person.hasMany("friends", {
  rate : Number
}, {}, { key: true });

Person.get(123, function (err, John) {
  John.getFriends(function (err, friends) {
    // assumes rate is another column on table person_friends
    // you can access it by going to friends[N].extra.rate
  });
});

If you prefer you can activate autoFetch. This way associations are automatically fetched when you get or find instances of a model.

var Person = db.define('person', {
  name : String
});
Person.hasMany("friends", {
  rate : Number
}, {
  key       : true, // Turns the foreign keys in the join table into a composite key
  autoFetch : true
});

Person.get(123, function (err, John) {
    // no need to do John.getFriends() , John already has John.friends Array
});

You can also define this option globally instead of a per association basis.

var Person = db.define('person', {
  name : String
}, {
    autoFetch : true
});
Person.hasMany("friends", {
  rate : Number
}, {
  key: true
});

Associations can make calls to the associated Model by using the reverse option. For example, if you have an association from ModelA to ModelB, you can create an accessor in ModelB to get instances from ModelA. Confusing? Look at the next example.

var Pet = db.define('pet', {
  name : String
});
var Person = db.define('person', {
  name : String
});
Pet.hasOne("owner", Person, {
  reverse : "pets"
});

Person(4).getPets(function (err, pets) {
  // although the association was made on Pet,
  // Person will have an accessor (getPets)
  //
  // In this example, ORM will fetch all pets
  // whose owner_id = 4
});

This makes even more sense when having hasMany associations since you can manage the many to many associations from both sides.

var Pet = db.define('pet', {
  name : String
});
var Person = db.define('person', {
  name : String
});
Person.hasMany("pets", Pet, {
  bought  : Date
}, {
  key     : true,
  reverse : "owners"
});

Person(1).getPets(...);
Pet(2).getOwners(...);

Promise support

ORM supports Promises via bluebird. Most methods which accept a callback have a Promise version whith a Async postfix. Eg:

orm.connectAsync().then().catch();
Person.getAsync(1).then();
Person.find({ age: 18 }).where("LOWER(surname) LIKE ?", ['dea%']).allAsync( ... );
Person.aggregate({ surname: "Doe" }).min("age").max("age").getAsync();

The exception here are hooks, which should return a Promise if they perform asynchronous operations:

beforeCreate: function () {
  return new Promise(function(resolve, reject) {
    doSomeStuff().then(resolve);
  }

Adding external database adapters

To add an external database adapter to orm, call the addAdapter method, passing in the alias to use for connecting with this adapter, along with the constructor for the adapter:

require('orm').addAdapter('cassandra', CassandraAdapter);

See the documentation for creating adapters for more details.

License

FOSSA Status

Comments
  • Saving model with auto-fetched relations causes stack overflow

    Saving model with auto-fetched relations causes stack overflow

    If a model has autoFetch true, and you fetch the model then try to save it, Node reports:

    RangeError: Maximum call stack size exceeded
    2 Aug 19:22:00 - [nodemon] app crashed - waiting for file changes before starting...
    

    If the auto-fetched field is overwritten it saves ok:

    db.Post.get(1337, function(e,p) {
        p.user = null;
        p.channel = null;
        p.template = null;
        p.save({ updated_at: new Date() }, function(err) {
            console.log('done')
        });
    });
    
    bug 
    opened by dirkmc 48
  • fields lowercase

    fields lowercase

    I used the Mysql World-database as example to test Orm. All the examples for fields are lowercase. Testing with find returned an empty array but the count was correct. It took me a long time to find out that the field defs in MySql table where mixed case. The empty array was not really helping... It also could suggest the find was empty? An error that the fieldname was not found would have been more helpfull?

    enhancement code added 
    opened by GoNode5 35
  • Added Q promises support for the whole API.

    Added Q promises support for the whole API.

    The main idea is that if you don't provide the callback parameter in any call to the API, then a promise is returned.

    So you can do things like this:

    return Person.create({name: "John", lastname: "Smithhhh"})
    .then(function(person) {
       person.lastname="Smith";
       return person.save();
    }).then(function () {
       console.log("Last name changed");
    }).fail(function(err) {
       console.log(err);
    });
    

    This modification maintains compatibility with old code and let start using promises in new code.

    For the ChainFind, only the run and the count returns a promise if no callback is provided.

    opened by jbaylina 28
  • Time zone is double-shifted when saving

    Time zone is double-shifted when saving

    Note that I ran this code at 19:21:01 EDT (New York time), which is 23:21:01 UTC (NY is four hours behind UTC). But when the value is stored to the database it has been shifted four hours again, to 03:21:01 UTC.

    var now = new Date();
    db.Test.create({
        created_at: now,
        mytext: 'test'
    }, function(err, data) {
        db.Test.get(data.id, function(err, newObj) {
            console.log(JSON.stringify(now));
            // "2013-08-18T23:21:01.979Z"
            console.log(JSON.stringify(newObj.created_at));
            // "2013-08-19T03:21:01.000Z"
        });
    });
    
    mysql> select id, created_at, UNIX_TIMESTAMP(created_at) from test where id = 5;
    +----+---------------------+----------------------------+
    | id | created_at          | UNIX_TIMESTAMP(created_at) |
    +----+---------------------+----------------------------+
    |  5 | 2013-08-18 23:21:01 |                 1376882461 |
    +----+---------------------+----------------------------+
    

    Taking the unix timestamp value above and putting it into the browser console shows that it is 23:21:01 EDT (NY time) when it should be 19:21:01 EDT:

    new Date(1376882461 * 1000);
    Sun Aug 18 2013 23:21:01 GMT-0400 (EDT)
    
    bug 
    opened by dirkmc 28
  • Create related ?

    Create related ?

    I didn't find it in the code nor in model.js, so I ask here : can I do something like this ?

    User.get(123, function (err, user) {
      user.getArticles().create(props, function (err, article) {
        // article.user_id === user.id
      });
    });
    
    opened by vendethiel 26
  • raw where clause

    raw where clause

    Hi diego, I was wondering if it's possible to do a find with a raw where clause? Some queries are too complex to model using orm.lt etc.

    For example I need to do this:

    Post.find(
      'id not in (' post_ids + ') AND channel_id in (' channel_ids ') AND changed_at > (' +
      '  SELECT min(changed_at) FROM posts p WHERE p.id in (' post_ids ')' +
      ')').run(...)
    
    enhancement 
    opened by dirkmc 22
  • Create associate items

    Create associate items

    With the autoFetch attribute, nested items are retrieved from associated tables.

    Is it possible to have the same work for post, e.g if i were to post

      Person.create([{
         name:"John", 
         pets:[
            {name:"Fido"},
            {name:"Tigger"}
         ]
      }], function(){... respond when done...});
    

    It would write items to the model which was associated with 'pets'

    I found a work around using afterCreate hook e.g.

      afterCreate : function(){
          // Loop through and insert any children
          for(var x in this){
            if( this.hasOwnProperty(x) && this[x] instanceof Array && x in models){
    
              for(var i=0;i<this[x].length;i++){
                this[x][i]['owner_id'] = this.id;
              }
    
              models[x].create(this[x], function(err){
                if(err){
                  console.log(err);
                }
                else{
                  console.log("Added "+i +" pets");
                }
              });
            }
          }
     }
    

    However i'd like it to be a little more abstract and have it know the reference to the child in question, e.g. not have to explicitily define it like i do with... this[x][i]['owner_id'] = this.id;

    Also i'd only like it to trigger the callback if this has been completed successfully. But there is no "next" parameter passed to this particular hook.

    Thanks in advance, great project.

    enhancement code added 
    opened by MrSwitch 21
  • More detailed documentation

    More detailed documentation

    Between the two documentation sources I've found for this library (the ReadTheDocs page and the readme.md) I still don't have a clear idea of all the methods, arguments, and options available in this library. Is there no simple list of these things, or have I missed something?

    opened by Fauntleroy 19
  • Custom condition

    Custom condition

    Hello dresende,

    thank you very much for your work on this project, it helps me a lot. I'am using your orm for accessing mysql database with about 30M records and it works fine. So now I'm looking for some way to add custom condition to where clause.

    Here is my SQL schema:

    CREATE TABLE `category` (
      `id` int(11) NOT NULL,
      `name` varchar(1024) COLLATE utf8_czech_ci NOT NULL,
      `url` varchar(200) COLLATE utf8_czech_ci NOT NULL,
      `leaf` tinyint(4) NOT NULL DEFAULT '0',
      `number_of_products` int(11) NOT NULL DEFAULT '0',
      `path` varchar(800) COLLATE utf8_czech_ci NOT NULL DEFAULT '',
      PRIMARY KEY (`id`),
      KEY `url` (`url`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci;
    
    CREATE TABLE `category_tree` (
      `predecessor_id` int(11) NOT NULL,
      `successor_id` int(11) NOT NULL,
      `distance` int(11) NOT NULL,
      PRIMARY KEY (`predecessor_id`,`successor_id`),
      KEY `FK_category_tree_successor` (`successor_id`),
      CONSTRAINT `FK_category_tree_predecessor` FOREIGN KEY (`predecessor_id`) REFERENCES `category` (`id`),
      CONSTRAINT `FK_category_tree_successor` FOREIGN KEY (`successor_id`) REFERENCES `category` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci;
    
    CREATE TABLE `product` (
      `id` int(11) NOT NULL,
      `name` varchar(512) COLLATE utf8_czech_ci NOT NULL,
      `description` text COLLATE utf8_czech_ci,
      `rating` int(11) DEFAULT NULL,
      `ean` varchar(20) COLLATE utf8_czech_ci DEFAULT NULL,
      `price` decimal(14,2) DEFAULT NULL,
      `image_url` varchar(1024) COLLATE utf8_czech_ci DEFAULT NULL,
      `date` date NOT NULL,
      PRIMARY KEY (`id`),
      KEY `price` (`price`),
      KEY `ean` (`ean`),
      KEY `name` (`name`(180)),
      KEY `date` (`date`),
      CONSTRAINT `FK_category_product` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci;
    
    CREATE TABLE `category_product` (
      `category_id` int(11) NOT NULL,
      `product_id` int(11) NOT NULL,
      PRIMARY KEY (`category_id`,`product_id`),
      KEY `product` (`product_id`),
      CONSTRAINT `FK_category_product_category` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`),
      CONSTRAINT `FK_category_product_product` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci;
    
    CREATE TABLE `property` (
      `id` int(11) NOT NULL,
      `name` varchar(200) COLLATE utf8_czech_ci NOT NULL,
      `description` text COLLATE utf8_czech_ci,
      `unit` varchar(512) COLLATE utf8_czech_ci DEFAULT NULL,  
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci;
    
    CREATE TABLE `property_value` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `value` varchar(512) COLLATE utf8_czech_ci NOT NULL,
      `property_id` int(11) NOT NULL,
      PRIMARY KEY (`id`),
      KEY `property_id_value` (`property_id`,`value`(200))
    ) ENGINE=InnoDB AUTO_INCREMENT=525900 DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci;
    
    CREATE TABLE `product_property_value` (
      `product_id` int(11) NOT NULL,
      `property_value_id`  int(11) NOT NULL,
      PRIMARY KEY (`product_id`,`property_value_id`),
      KEY `property_value` (`property_value_id`),
      CONSTRAINT `FK_product_property_value_product` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`),
      CONSTRAINT `FK_product_property_value_property_value` FOREIGN KEY (`property_value_id`) REFERENCES `property_value` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci;
    
    CREATE TABLE `category_property` (
      `category_id` int(11) NOT NULL,
      `property_id` int(11) NOT NULL,
      PRIMARY KEY (`category_id`,`property_id`),
      KEY `property_id` (`property_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci;
    

    I'm getting products for category by:

    ...
    Category(category_id).getProducts( ...
    ...
    

    SQL statement looks like this:

    SELECT 
        `t1`.`id`, `t1`.`name`, `t1`.`ean`, `t1`.`price`, `t1`.`date`, `t1`.`description`, `t2`.* 
    FROM 
        `product` `t1` 
        JOIN `category_product` `t2` ON `t2`.`product_id` = `t1`.`id` 
    WHERE 
        (`t2`.`category_id` = 813) 
    ORDER BY 
        `t1`.`name` ASC 
    LIMIT 250 OFFSET 1250 
    

    But now I need to add filtering by property values which means adding another condition:

    SELECT 
        `t1`.`id`, `t1`.`name`, `t1`.`ean`, `t1`.`price`, `t1`.`date`, `t1`.`description`, `t2`.* 
    FROM 
        `product` `t1` 
        JOIN `category_product` `t2` ON `t2`.`product_id` = `t1`.`id` 
    WHERE 
        (`t2`.`category_id` = 813)  
        AND EXISTS(
            SELECT * FROM `product_property_value` WHERE `product_id` = `t1`.`id` AND `property_value_id` = 4564
        )
    ORDER BY 
        `t1`.`name` ASC 
    LIMIT 250 OFFSET 1250 
    

    So is there any correct way to do that?

    Thank you very much, kody

    bug code added 
    opened by czkody 19
  • Question - why do hasMany relationships require a separate join table?

    Question - why do hasMany relationships require a separate join table?

    Hi,

    I'm just coming up to speed with ORM2. Great work so far!

    I'm curious why you chose to implement hasMany by relying on a third join table between the associated models? In Downstairs (the ORM I created but probably won't continue) I assumed that if a Foo hasMany Bars, then the Bar table would have a foreign key called foo_id.

    https://github.com/nicholasf/downstairs.js/blob/master/lib/collection.js#L127

    Cheers, Nicholas

    code added 
    opened by nicholasf 19
  • No associations defined error

    No associations defined error

    I have a users model with hasMany('addresses', {description:String}, db.model.addresses) when I try to use user.setAddresses() or user.addAddresses()it throws an error saying "No associations defined".

    I checked out the code line that threw the error (line 398, Many.js file) and it is an if statement checking if Associations.length === 0, but as it seems, Associations never gets an object pushed, it seems like it would always have length = 0.

    What could I be doing wrong ?

    opened by figalex 18
  • findBySmth has doubles

    findBySmth has doubles

    Hi. i broke my head.

    I have this: this.req.models.Tour.findByInfo({ Charter: this.req.query.Charter, }, { autoFetch: false }).where("Active = 1",(err, tours) => { this.res.end(JSON.stringify(tours)) })

    This is what I get. At the output, I get:

    [ { "Title": "Тур в горы", "Rating": 9, "Description": "Ахуенный тур", "Active": true, "MinDate": null, "MaxDate": null, "id": 1, "owner_id": 1, "town_id": 1 }, { "Title": "Тур в горы", "Rating": 9, "Description": "Ахуенный тур", "Active": true, "MinDate": null, "MaxDate": null, "id": 1, "owner_id": 1, "town_id": 1 }, { "Title": "Тур в горы", "Rating": 9, "Description": "Ахуенный тур", "Active": true, "MinDate": null, "MaxDate": null, "id": 1, "owner_id": 1, "town_id": 1 }, { "Title": "Тур в горы", "Rating": 9, "Description": "Ахуенный тур", "Active": true, "MinDate": null, "MaxDate": null, "id": 1, "owner_id": 1, "town_id": 1 } ]

    I understand what the problem is, so JOIN works. SQL:

    SELECT t1.Title, t1.Rating, t1.Description, t1.Active, t1.MinDate, t1.MaxDate, t1.id, t1.owner_id, t1.town_id FROM Tour t1 JOIN TourInfo t2 ON t2.tour_id = t1.id WHERE (t2.Charter = '1' AND t2.Price BETWEEN 0 AND 999999999) AND (Active = 1)

    BUT i NEED so SQL:

    SELECT DISTINCT(t1.id), t1.Title, t1.Rating, t1.Description, t1.Active, t1.MinDate, t1.MaxDate, t1.owner_id, t1.town_id FROM Tour t1 JOIN TourInfo t2 ON t2.tour_id = t1.id WHERE (t2.Charter = '1' AND t2.Price BETWEEN 0 AND 999999999) AND (Active = 1)

    OR

    SELECT t1.id, t1.Title, t1.Rating, t1.Description, t1.Active, t1.MinDate, t1.MaxDate, t1.owner_id, t1.town_id FROM Tour t1 JOIN TourInfo t2 ON t2.tour_id = t1.id WHERE (t2.Charter = '1' AND t2.Price BETWEEN 0 AND 999999999) AND (Active = 1) GROUP BY t1.id

    opened by naturalcod 0
  • IF condition

    IF condition

    Hi, sorry but I'm somehow confused on how to exactly do query condition for IF and IS NULL

    I have this particular SQL query but not sure how to convert it to ORM.

    WHERE has_sent = 0 AND messenger_messages.create_date >= IF(users.last_login IS NULL, ( Curdate() - interval 1 month ), users.last_login + interval 5 minute)

    Hope you can help. Thanks!

    opened by linfiesto 0
  • Group by Month?

    Group by Month?

    How can I group my results by month? I want to get sum of orders in all months of the year. I tried using .groupBy("MONTH(createdAt)") but it returns "undefined"

    opened by GhoSTBG 0
  • Validations not working?

    Validations not working?

    I'm trying to validate the input data but when I do console.log(err) I'm receiving 'null'

    Code:

      <!-- models.js -->
      var cluster = db.define('cluster', {
        name : String,
       }, {
         validations: {
           name: db.enforce.notEmptyString('Oops! Your cluster needs a name.'),
           name: db.enforce.unique({ ignoreCase : true }, 'Oops! Cluster with that name already exist.')
         }
      });
    
     <!-- Cluster Controller -->
     //TODO: Make validations for the cluster using Node-ORM2
      add: function(m, db, socket) {
    
        var cluster = new db.models.cluster({ name : m.name, shop_id : m.shop, display_id : m.display });
        cluster.save(function(err) {
          console.log(err)
        })
      }
    
    opened by GhoSTBG 1
  • Missing primary key value after create

    Missing primary key value after create

    Version:

    package:
      "dependencies": {
        "bluebird": "^3.5.1",
        "mysql": "^2.15.0",
        "orm": "^4.0.2",
        "orm-transaction": "0.0.2",
        "request": "^2.83.0",
        "validator": "^8.2.0"
      }
    
    node -v:
    v6.10.2
    
    db driver: 
    ORM.connectAsync({
                    host: obj.host,
                    user: obj.user,
                    password: obj.password,
                    database: obj.databaseName,
                    protocol: 'mysql',
                    port: obj.port,
                    query: {
                        debug: isDebug,
                        // timezone : 'GMT+8'
                    }
                })
    
    

    Model:

    const user = require('../user');
    const schedule = db.define('schedule', {
        id: {type: 'serial', key: true},
        title: {type: 'text', size: 128, key: true},
        text: {type: 'text', size: 512},
        is_todo_list: {type: 'boolean', index: true,defaultValue:false},   
        type: {type: 'enum', values: ['SELF', 'BROADCAST', 'OTHER'], index: true, required: true},
        created_at: {type: 'date', time: true, index: true}, 
        start_at: {type: 'date', time: true, index: true}, 
        end_at: {type: 'date', time: true, index: true},  
    }, {
        hooks: {
            afterAutoFetch: function () {
                this.created_at = new Date(this.created_at).getTime();
                this.start_at = new Date(this.start_at).getTime();
                this.end_at = new Date(this.end_at).getTime();
            },
            beforeValidation: function () {
                this.created_at = new Date(this.created_at);
                this.start_at = new Date(this.start_at);
                this.end_at = new Date(this.end_at);
            }
        }
    });
    schedule.hasMany('receiver', user);
    

    Create:

                console.log('obj :',obj);
                schedule.create(obj, (e, r) => {
                    console.log('e,r :',e,JSON.stringify(r));
                    if (e) {
                        reject(e);
                    } else {
                        resolve(r);
                    }
                });
    

    And console log shows:

    obj : { title: 'title',
      text: 'text',
      is_todo_list: true,
      type: 'OTHER',
      start_at: 1517917402000,
      end_at: 1517967402000,
      receiver: [ 2, 3 ] }
    [SQL/mysql] INSERT INTO `schedule` (`title`, `text`, `is_todo_list`, `type`, `start_at`, `end_at`, `created_at`, `author_id`) VALUES ('title', 'text', 1, 'OTHER', '2018-02-06 19:43:22.000', '2018-02-07 09:36:42.000', '1970-01-01 08:00:00.000', NULL)
    [SQL/mysql] SELECT `t1`.`id`, `t1`.`name`, `t1`.`level`, `t1`.`master_id` FROM `department` `t1` JOIN `user_department` `t2` ON `t2`.`department_id` = `t1`.`id` WHERE `t2`.`user_id` = 2
    [SQL/mysql] SELECT `t1`.`id`, `t1`.`name`, `t1`.`level`, `t1`.`master_id` FROM `department` `t1` JOIN `user_department` `t2` ON `t2`.`department_id` = `t1`.`id` WHERE `t2`.`user_id` = 3
    [SQL/mysql] DELETE FROM `schedule_receiver` WHERE `schedule_id` IS NULL AND `undefined` = 'title'
    e,r : { Error: ER_BAD_FIELD_ERROR: Unknown column 'undefined' in 'where clause'
        at Query.Sequence._packetToError (D:\projects\xxxxxxx\node_modules\mysql\lib\protocol\sequences\Sequence.js:52:14)
        at Query.ErrorPacket (D:\projects\xxxxxxx\node_modules\mysql\lib\protocol\sequences\Query.js:77:18)
        at Protocol._parsePacket (D:\projects\xxxxxxx\node_modules\mysql\lib\protocol\Protocol.js:279:23)
        at Parser.write (D:\projects\xxxxxxx\node_modules\mysql\lib\protocol\Parser.js:76:12)
        at Protocol.write (D:\projects\xxxxxxx\node_modules\mysql\lib\protocol\Protocol.js:39:16)
        at Socket.<anonymous> (D:\projects\xxxxxxx\node_modules\mysql\lib\Connection.js:103:28)
        at emitOne (events.js:96:13)
        at Socket.emit (events.js:188:7)
        at readableAddChunk (_stream_readable.js:176:18)
        at Socket.Readable.push (_stream_readable.js:134:10)
        at TCP.onread (net.js:551:20)
        --------------------
        at Protocol._enqueue (D:\projects\xxxxxxx\node_modules\mysql\lib\protocol\Protocol.js:145:48)
        at Connection.query (D:\projects\xxxxxxx\node_modules\mysql\lib\Connection.js:208:25)
        at Driver.execSimpleQuery (D:\projects\xxxxxxx\node_modules\orm\lib\Drivers\DML\mysql.js:103:13)
        at Driver.remove (D:\projects\xxxxxxx\node_modules\orm\lib\Drivers\DML\mysql.js:216:8)
        at run (D:\projects\xxxxxxx\node_modules\orm\lib\Associations\Many.js:339:25)
        at Object.value (D:\projects\xxxxxxx\node_modules\orm\lib\Associations\Many.js:352:9)
        at Object.value (D:\projects\xxxxxxx\node_modules\orm\lib\Associations\Many.js:298:40)
        at saveAssociation (D:\projects\xxxxxxx\node_modules\orm\lib\Instance.js:279:25)
        at _saveManyAssociation (D:\projects\xxxxxxx\node_modules\orm\lib\Instance.js:332:7)
        at saveAssociations (D:\projects\xxxxxxx\node_modules\orm\lib\Instance.js:336:7)
        at D:\projects\xxxxxxx\node_modules\orm\lib\Instance.js:218:14
        at Query._callback (D:\projects\xxxxxxx\node_modules\orm\lib\Drivers\DML\mysql.js:196:12)
        at Query.Sequence.end (D:\projects\xxxxxxx\node_modules\mysql\lib\protocol\sequences\Sequence.js:88:24)
        at Query._handleFinalResultPacket (D:\projects\xxxxxxx\node_modules\mysql\lib\protocol\sequences\Query.js:139:8)
        at Query.OkPacket (D:\projects\xxxxxxx\node_modules\mysql\lib\protocol\sequences\Query.js:72:10)
        at Protocol._parsePacket (D:\projects\xxxxxxx\node_modules\mysql\lib\protocol\Protocol.js:279:23)
      code: 'ER_BAD_FIELD_ERROR',
      errno: 1054,
      sqlMessage: 'Unknown column \'undefined\' in \'where clause\'',
      sqlState: '42S22',
      index: 0,
      sql: 'DELETE FROM `schedule_receiver` WHERE `schedule_id` IS NULL AND `undefined` = \'title\'',
      instance: 
       { id: [Getter/Setter],
         title: [Getter/Setter],
         text: [Getter/Setter],
         is_todo_list: [Getter/Setter],
         type: [Getter/Setter],
         created_at: [Getter/Setter],
         start_at: [Getter/Setter],
         end_at: [Getter/Setter],
         author_id: [Getter/Setter],
         receiver: [Getter/Setter] } } undefined
    

    If I remove hasMany object 'receiver: [ 2, 3 ]', the result will be:

    obj : { title: 'title',
      text: 'text',
      is_todo_list: true,
      type: 'OTHER',
      start_at: 1517917402000,
      end_at: 1517967402000 }
    [SQL/mysql] INSERT INTO `schedule` (`title`, `text`, `is_todo_list`, `type`, `start_at`, `end_at`, `created_at`, `author_id`) VALUES ('title', 'text', 1, 'OTHER', '2018-02-06 19:43:22.000', '2018-02-07 09:36:42.000', '1970-01-01 08:00:00.000', NULL)
    e,r : null {"title":"title","text":"text","is_todo_list":true,"type":"OTHER","created_at":"1970-01-01T00:00:00.000Z","start_at":"2018-02-06T11:43:22.000Z","end_at":"2018-02-07T01:36:42.000Z","author_id":null}
    

    You can see after create, id is missing. I can't understand why because my other models are more complicated but they don't have this issue.

    opened by goodman3 0
  • findByAssociation has problems with auto generated coloumn by `.hasOne` method with `mapsTo` option.

    findByAssociation has problems with auto generated coloumn by `.hasOne` method with `mapsTo` option.

    // Defining Model
    LikesCut.hasOne('target', Cuts, {reverse: 'likes', field: 'targetId', mapsTo: 'target_id', required: true})
    
    // CASE 1 : ER_BAD_FIELD_ERROR: Unknown column 't1.targetId' in 'on clause'
    LikesCut.findByTarget({}).runAsync()
    // CASE 2 : ER_BAD_FIELD_ERROR: Unknown column 't2.targetId' in 'on clause'
    Cuts.findByLikes({}).runAsync()
    

    it seems to tying join with wrong column name. is there something wrong in my codes or isn't it prepared yet?

    opened by reumia 0
Releases(v3.1.0)
  • v3.1.0(May 9, 2016)

  • v3.0.0(May 3, 2016)

    Disable identity cache by default & rename from cache to identityCache.

    The so called 'cache' wasn't really a cache, and this fact causes many problems. Closes #350 Closes #564 Closes #626 Closes #672 Closes #684 Closes #694 Closes #721

    Source code(tar.gz)
    Source code(zip)
  • v2.1.30(Jan 28, 2016)

  • v2.1.26(May 28, 2015)

  • v2.1.24(Mar 24, 2015)

  • v2.1.2(Sep 18, 2013)

    • Fixes stack overflow on instance.save() with a reversed hasOne association (#338)
    • Reverts should dev dependency to 1.2.2 (newer version was causing problems)
    • When using postgres you can now use [email protected] (unless when connecting to Heroku - use 2.5.0)
    Source code(tar.gz)
    Source code(zip)
  • v2.1.1(Sep 13, 2013)

    • Add TypeScript interface
    • Allow custom join tables (#276)
    • Fixes stack overflow when saving auto-fetched model with relations (#279)
    • Unique validator can be scoped and case insensitive (#288)
    • Allow async express middleware (#291)
    • Allow finding by associations (#293)
    • Fix sqlite find with boolean (#292)
    • Fix afterLoad hook error handling (#301)
    • Allow auto-escaping for custom queries (#304)
    • Add support for custom property types (#305)
    • Allow ordering by raw sql - .orderRaw() when chaining (#308, #311)
    • Fix saving Instance.extra fields (#312)
    • Fix NaN handling (#310)
    • Fix incorrect SQL query (#313)
    • Deprecated PARAM_MISSMATCH ErrorCode in favour of correctly spelt PARAM_MISMATCH (#315)
    • Add promises to query chain (#316)
    • Adds a test for hasMany.delAccessor with arguments switched (#320)
    • Allow passing timezone in database connection string, local timezone is now default (#325, #303)
    • Adds ability to call db.load() with multiple files (closes #329)
    • For mysql driver, when using pool, use con.release() instead of con.end() (if defined) (closes #335)
    • Passes error from afterLoad hook to ready event
    • Most errors now have a model property
    • Adds connection.pool and connection.debug settings
    • Fixes throw when calling ChainFind.first() or .last() and it has an error
    • Removes upper limit on VARCHAR column size
    • Allows multi-key models to support hasMany
    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(Aug 3, 2013)

    • Adds License (MIT) file (closes #271)
    • Make Model.get respect Model autoFetch default value (#277)
    • Changes the way ":" is added to sqlite db paths (#270)
    • Fixes duplicated debug lines for postgres (#258)
    • Fixes not saving associations if no changes (other than associations) are made (#256)
    • Fixes autoFetch being discarded in Model.get options (closes #266)
    • Adds beforeDefine to plugins (#263)
    • Allows user to pass an object to extendsTo.setAccessor instead of an instance (detected via #250)
    • Changes autoFetch to avoid autofetching if instance is not saved (it's new!) (#242)
    • Changes validations and predefined validators to use [email protected]
    • Adds support for setting properties.association_key to be a function (name, field)
    • Passes connection settings to database drivers
    • Creates initial mongodb driver and 'mongo' driver alias
    • Allow querying chainfind with sql conditions
    • Allow passing extra options to extended models
    • Allow big text fields
    • Allow before* hooks to modify the instance
    • Fixes #226 - hasOne delAccessor not working
    • Adds Utilities.getRealPath to look for the real path to load based on the file where it was called from (for db.load and db.use)
    • Fixes Model.aggregate().call() to accept no arguments except function name
    • Fix problem with extendsTo and custom key types
    • Better association typing and multikey support
    Source code(tar.gz)
    Source code(zip)
  • v2.0.15(Jul 11, 2013)

    • Support for 'point' type as a property (#221)
    • .call() in aggregates for generic functions (#204)
    • Adds hook afterAutoFetch triggered after extending and auto fetching (if any) associations (#219)
    • Adds predefined validator .password()
    • Adds ability to have the afterLoad hook blocking (#219)
    • Changes Model.create() to wait for createInstance callback instead of using the returned value
    • Fixes problem with hasOne associations for none persisted instances and autoFetch active just blocking
    • Refactored Model.hasOne() constructor to be able to mix parameters
    • Fixes reversed hasOne association on the reversed model not being correctly saved (#216)
    • Changes Model.hasMany.addAccessor to throw just like .setAccessor when no associations are passed
    • Adds ability to pass an Array to hasMany.hasAccessor and also not passing any instance to hasAccessor and have it check for any associated item
    • Exposes Model methods to change hooks after model definition
    • Fixes postgres driver not returning numbers for number columns
    • Fixes passing json object instead of instances to Model.create() associations (#216)
    • Passes Model to Instance directly, changes Instance to use Model.properties instead of opts.properties
    • Exposes Model.properties
    • Removes old Property.js throw error in favour of new one
    • Adds initial Model.extendsTo(name, properties[, opts])
    • Avoids redefining properties in instances
    • Adds ErrorCodes.NOT_DEFINED
    • Adds db.drop() - similar to db.sync()
    • Changes hasMany.getAccessor to support order as string (closes #196)
    • Handle django string formatted sqlite datetime
    • Many bug fixes
    Source code(tar.gz)
    Source code(zip)
  • v2.0.14(Jul 2, 2013)

    • Changes many errors to use the ErrorCodes generator (#206)
    • Changes Model.aggregate() to support multiple orders when calling .order() (#207)
    • Changes Readme.md sqlite3 version and adds warning.
    • Fix wrong import of debug output for aggregate functions
    • Fix orm when running on node v0.6 (at least) and module not found error has no code property
    • Adds model.namePrefix setting (#203)
    • Fixes bug when passing an array (object) of ids but no options object
    • Only mark model as dirty if a property has really changed
    • Fix hasOne infinite loop
    • WIP: Fix hasOne infinite loop & migrate tests to mocha
    • Fixes ipv4 predefined validator match string (it was not matching correctly!)
    • Fixes Model.get() when passing cache: false and model has cache: true
    • Creates Singleton.clear() to clear cache, exports singleton in orm
    • Fix required property model.save only threw a single error with returnAllErrors = true
    • Fixes some hasMany association usage of Association.id to check for real id property name (#197)
    • Changes db.load() to return value from loaded and invoked function (#194)
    • Adds possibility to add a callback to ChainFind.find() (#190)
    • Adds .findByX(...) to .hasOne("X", ...)
    • Allow db.load() to work outside of module.exports
    • Fix mysql driver for non-autoincrement key
    • Test framework moving to mocha, not complete yet
    • Adds make cov to make for a test coverage
    • Many other bug fixes
    Source code(tar.gz)
    Source code(zip)
AlaSQL.js - JavaScript SQL database for browser and Node.js. Handles both traditional relational tables and nested JSON data (NoSQL). Export, store, and import data from localStorage, IndexedDB, or Excel.

Please use version 1.x as prior versions has a security flaw if you use user generated data to concat your SQL strings instead of providing them as a

Andrey Gershun 6.1k Jan 9, 2023
A typescript data mapping tool. To support mutual transforming between domain model and orm entity.

ts-data-mapper A typescript mapping tool supports mutual transforming between domain model and orm entity. In most case, domain model is not fully com

zed 8 Mar 26, 2022
MongoDB object modeling designed to work in an asynchronous environment.

Mongoose Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose supports both promises and callbacks. Do

Automattic 25.2k Dec 30, 2022
In-memory Object Database

limeDB What is LimeDB LimeDB is object-oriented NoSQL database (OOD) system that can work with complex data objects that is, objects that mirror those

Luks 2 Aug 18, 2022
A simple, fast, reliable Object Relationship Manager for Bun.

Burm is an object relational manager for Bun, the fastest Javascript Engine. The name is a merge of "Bun" and "ORM", forming "Burm". Pronounce it howe

William McGonagle 70 Dec 28, 2022
The Pinia plugin to enable Object-Relational Mapping access to the Pinia Store.

pinia-orm Intuitive, type safe and flexible ORM for Pinia based on Vuex ORM Next ✨ Release Notes ?? Documentation Help me keep working on this project

Gregor Becker 148 Dec 31, 2022
Prisma is a next-generation object–relational mapper (ORM) that claims to help developers build faster and make fewer errors.

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Rhodin Emmanuel Nagwere 1 Oct 8, 2022
Node.js object hash library with properties/arrays sorting to provide constant hashes. It also provides a method that returns sorted object strings that can be used for object comparison without hashes.

node-object-hash Tiny and fast node.js object hash library with properties/arrays sorting to provide constant hashes. It also provides a method that r

Alexander 73 Oct 7, 2022
Lovefield is a relational database for web apps. Written in JavaScript, works cross-browser. Provides SQL-like APIs that are fast, safe, and easy to use.

Lovefield Lovefield is a relational database written in pure JavaScript. It provides SQL-like syntax and works cross-browser (currently supporting Chr

Google 6.8k Jan 3, 2023
AlaSQL.js - JavaScript SQL database for browser and Node.js. Handles both traditional relational tables and nested JSON data (NoSQL). Export, store, and import data from localStorage, IndexedDB, or Excel.

Please use version 1.x as prior versions has a security flaw if you use user generated data to concat your SQL strings instead of providing them as a

Andrey Gershun 6.1k Jan 9, 2023
Visualize, modify, and build your database with dbSpy! An open-source data modeling tool to facilitate relational database development.

Visualize, modify, and build your database with dbSpy! dbSpy is an open-source data modeling tool to facilitate relational database development. Key F

OSLabs 115 Dec 22, 2022
Types generator will help user to create TS types from JSON. Just paste your single object JSON the Types generator will auto-generate the interfaces for you. You can give a name for the root object

Types generator Types generator is a utility tool that will help User to create TS Interfaces from JSON. All you have to do is paste your single objec

Vineeth.TR 16 Dec 6, 2022
A global H3 population dataset optimized for consumption in Helium mapping projects.

H3 Population Helium A global population dataset based on Uber's H3 mapping system and seeded from the open source Kontur Population dataset. Optimize

Arman Dezfuli-Arjomandi 6 Apr 25, 2022
Collect and generate mapping from file-based routers

roullector: route collector Collect and generate route data from a file-based router such as svelte-kit's What this does: show / hide <!-- before -->

Quang Phan 4 Apr 9, 2022
A typescript data mapping tool. To support mutual transforming between domain model and orm entity.

ts-data-mapper A typescript mapping tool supports mutual transforming between domain model and orm entity. In most case, domain model is not fully com

zed 8 Mar 26, 2022
PEARL (Planetary Computer Land Cover Mapping) Platform API and Infrastructure

PEARL API & Infrastructure PEARL is a landcover mapping platform that uses human in the loop machine learning approach. This repository contains the A

Development Seed 47 Dec 23, 2022
Mind Mapping to excel, or excel to .xmind file

Mind Mapping To Excel Project setup Prepare project npm install 1、Fetch data and generate excel Open the Mind Mapping like this Process On Mind Mappi

xuzelin995 3 May 5, 2022
Userland module that implements the module path mapping that Node.js does with "exports" in package.json

exports-map Userland module that implements the module path mapping that Node.js does with "exports" in package.json npm install exports-map Usage co

Mathias Buus 9 May 31, 2022
NoExGen is a node.js express application generator with modern folder structure, namespace/project mapping and much more! It contains preconfigured Settings and Routing files, ready to be used in any project.

Installation $ npm install -g noexgen Quick Start You can use Node Package Execution to create your node-express application as shown below: Create th

Souvik Sen 7 Oct 8, 2022
An object-oriented API for business analytics

dimple Dimple is an object-oriented API allowing you to create flexible axis-based charts using d3.js. The intention of this project is to allow analy

AlignAlytics 2.7k Dec 22, 2022