Taffy DB : Getting Started with your first bite of Taffy
Home | Download Taffy DB | Feedback/Bugs | FAQ  

Getting Started: Your first bite of Taffy

Quick overview:



Note: Taffy DB has a series of JavaScript utility functions that are available as public methods and may be of use in your applications.

 

Creating Collections

You start by creating a Taffy collection. To do this you pass in an array of similar objects.

Let's say you have a collection of four friends:

var friends = new TAFFY(
[
{name:"Bob",
  gender:"M",
  married:"No",
  age:25,
  state:"NY",
  favorite_foods:["pizza","tacos"]},
 {name:"Joyce",
  gender:"F",
  married:"No",
  age:29,
  state:"WA",
  favorite_foods:["salad","cheese sticks"]},
 {name:"Dan",
  gender:"M",
  married:"No",
  age:29,
  state:"MT",
  favorite_foods:["pizza","hamburgers","BLTs"]},
 {name:"Sarah",
  gender:"F",
  married:"No",
  age:21,
  state:"ID",
  favorite_foods:["pizza","sushi"]}
  ]
)
		

Now you have a Taffy collection of four friends. Just pass Taffy an array of objects (what you might get back from a JSON web service, for example) and you'll get back a collection of methods to rapidly work with those objects. You can also pass in a an unevaluated JSON string object and TAFFY will automatically parse it.

 

Find

Now, let's see if we can find friends who are older than 22:

friends.find({age:{greaterthan:22}});
		

This returns an array of the index values that match your query.

To do a query you call the find method and pass it an obj. This is similar to a where clause in SQL and tells the script you want all records where "age is greater than 22". The find method returns an array of indexes for matching records (objects).

Can we find friends that live in Washington, Montana, and Idaho?

friends.find({state:["WA","MT","ID"]});
		

Similar to the query above, but since we are doing a one to one (equal) comparison we can omit the additional syntax. Also, if you pass an array of values to the find method it will check all of them automatically. This would be similar to an IN statement in SQL.

For more on all the cool stuff you can do with find check out the advanced queries section.

 

Update

Ok, but how do you update your collection to note that your friend Joyce is now married and lives in New York?

friends.update(
	{
	state:"CA",
	married:"Yes"
	},
	{
	name:"Joyce"
	}
	);
		

The update method takes an object that defines how you want the data to be changed and an object (where clause) that tells you how to find the particular records to update.

This would be the same as calling the update with either the index number you want to update or with the result of a find. Example:

friends.update({state:"CA",married:"Yes"},1);
		

Or

friends.update(
	{
	state:"CA",
	married:"Yes"
	},
	friends.find(
		{name:"Joyce"}
		)
	); 	
		

Note: If you run update without a 2nd object (where clause) then all records will be updated.

 

Insert

Inserting is simple and works as you would expect:

friends.insert(
	{name:"Brian",
	gender:"M",
	married:"No",
	age:52,
	state:"FL",
	favorite_foods:["fruit","steak"]
	});
		

Note: You can also pass in an array of new objects which will each be inserted.

 

Remove

Deleting is also simple, but because delete is a reserved word in JavaScript we have to call by another name:

friends.remove({name:"Brian"});
		
 

OrderBy

You can also sort (order) the collection in a pretty simple manner:

friends.orderBy(["age",{"name":"desc"}]);
		

This sorts by age asc and then name descending. You can sort by as many columns as you want.

Taffy DB also you can sort in a logical manner which would sort a collection in the manner a human would expect:

		
var keys = new TAFFY([
{name:"12abc"},
{name:"abc343"},
{name:"1abc"},
{name:"23abc"}
]);

keys.orderBy({name:"logical"});

This would order the keys in the order a human would expect them. You can also use logicaldesc.

Note: You can also pass a function to the orderBy method in a similar manner as passing a function to JavaScript's array.sort() method.

 

ForEach

Doing stuff with your friends is far more interesting than simply having them. For that we use the forEach method which takes a function and applies it to each record in the collection:

friends.forEach(function (f,n) {alert(f.name)});
		

The first argument is the record object and the second argument is the index number of that record.

You can also limit the records it is applied to:

friends.forEach(
	function (f,n) {alert(f.name);},
	{favorite_foods:{has:"pizza"}}
);
		

This also shows how you can use has to compare an array or object column in the collection against your query text. Any record where one of the favorite_foods is "pizza" will be returned by this lookup.

You can also modify each record by returning a copy of it from your function. If you return nothing than no change will be made.

friends.forEach(
    function (f,n) {f.age = f.age+1; return f;}
);
		

Note, you can break out of a forEach loop by returning TAFFY.EXIT

 

Get / First / Last

So all this is fine and dandy, but how do you get your friends?

friends.get({name:"Joyce"});
		

Get returns an array of objects. To get just the first object you can call first(). To get just the last object you can call last(). To get all of the records just call get() without passing in an object to do a "where" lookup.

 

Stringify

Stringify works a lot let get only it returns a string version of a JavaScript object for use with Ajax web services.

friends.stringify({name:"Joyce"});
		

Or

friends.stringify();
		

 

Templates

You can use templates to add default values to your collection and minimize your own code when working with data. A template is an object that will be used as the base object for any new inserts into your collection. Unless your new record overwrites the value in a template TaffyDB will use the template value to populate the column.

You setup a template by calling collection.config.set("template",{}). You can remove a template by calling collection.config.set("template",null). A template is auto applied to every record in your collection when you set it.

This example adds a template to the friends collection and defaults email and phone values to "none". Any friend that already has those values will not be impacted by the template.

friends.config.set("template",
		{email:"none",
		phone:"none"}
);
        

You can also use collection.applyTemplate to apply a template to only a subset of records. Note that the template is only applied once in this insistence and will not impact future inserts into the collection or changes to these records. This example adds a "spouse" field to any married friend.

friends.applyTemplate(
	{"spouse":"unknown"},
	{married:"Yes"}
);
		

Note: you can access the current template set on a collection by calling collection.config.get("template").

 

Events

There are three events you can use within Taffy DB to help build your applications. They are:

  • onInsert(newObj) - which fires each time a record is inserted.
  • onUpdate(updateObj,originalObj) - which fires each time a record is updated.
  • onRemove(removedObj) - which fires each time a record is removed.


You can assign functions to this methods to do tasks when these events happen. Example:

friends.onRemove = function (r) {
	alert(r.name + " was removed");
};
friends.remove();
		

 

Advanced Queries

Since almost all of the methods in Taffy DB have you doing lookups, it is important to understand how powerful this feature is.

Using the find method detailed above you can pass in any number of filters to narrow your results.

Example:

friends.find({state:["WA","MT","ID"],
              age:{greaterthan:22}});
		

Here you will find only friends in these three states who are older than 22. Adding filters to a query is a lot like using the AND statement in a SQL where clause.

Note: you can reverse the logic for a filter by adding the bang (!) sign before the name. This would be similar to a != operator in standard SQL. This applies to all filter types.

Example (find friends not in Washington):

friends.find({state:{"!is":"WA"});
		

There are a total 17 different ways to filter your Taffy collection:

  • equal (default) (shorthand is)
    Collection matches text or number.
  • startswith (shorthand starts)
    Collection startswith text.
  • endswith (shorthand ends)
    Collection ends with text.
  • greaterthan (shorthand gt)
    Collection greater than number.
  • lessthan (shorthand lt)
    Collection less than number.
  • has
    [Collection] contains object, text, or key.
  • hasAll
    [Collection] contains all object, text, or keys defined in an array.
  • regexppass (shorthand regex)
    Collection passes regular expression.
  • like
    Collection like text.
  • notlike
    Collection not like text.
  • isSameObject
    Collection object value matches object.
  • isSameArray
    Collection array value matches array.
  • length
    Collection value length equals number (see below).

Using length filters

By using the length filter you can find strings and arrays based on their length. The simple ways is with an one to one match:

friends.find({state:{length:15});
		

The other way is by using one of the other methods above. This is a good way to find lengths over or below a value.

friends.find({state:{length:{gt:10}});
		

Type based queries

Version 1.4 of Taffy DB introduced a number of methods to filter based on type. Since Taffy DB allows you to store any data type in any column this can be useful for filtering on a multi-type column.

Here are you options for type filtering:

  • isString
    Collection is a string.
  • isNumber
    Collection is a number.
  • isArray
    Collection is an array.
  • isObject
    Collection is an object.
  • isBoolean
    Collection is a boolean (true/false).
  • isFunction
    Collection is a function.
  • isNull
    Collection is null.
  • isUndefined
    Collection is undefined.
  • isNumeric
    Collection contains only numbers.
  • isTAFFY
    Collection column is a Taffy DB collection.

To use these filters you'll need to pass a true or false value to match against.

Example:

friends.find({state:{isArray:true}});
		

Building efficient queries

In addition to being able to filter in many different ways and combine filters to perform more complex queries, you can also optimize your queries by passing the find method a list of indexes to check against your query instead of the whole collection.

Example:

friends.find({state:["WA","MT","ID"],
              age:{lt:50}},
              [0,2]);
		

Every call to the find method will require that every record in the collection be checked at least once. For complex queries and large collection this can require a lot of looping. Taffy DB automatically "narrows" results as it filters (with the second filter only looking at the records that passed the first filter, and so on). But sometimes that isn't enough. In the example above we limited the results by passing in a second argument: an array of indexes to be checked. This is a way to keep Taffy DB from scanning the whole collection if you already know which records are likely to apply.