-
Notifications
You must be signed in to change notification settings - Fork 40
CFMongoDB Object Mapper Syntax (proposed)
This is proposed syntax and subject to change. Unstable code can be found in the 0.9 branch.
There are 2 recommended ways to create persistent objects in a MongoDB datastore:
(1) Extending cfmongodb.components.MongoDocument, and
(2) Using the mongo.new_doc() factory method.
This provides 2 different approaches to generating the same types of objects. There are other ways, too [to do].
This is similar to CF9’s ORM syntax where you specify the fields you intend to persist as cfproperty
tags. Though not required, this articulates what you intend to persist and initializes the model/data with default values (if any). The MongoDocument class has methods for storing and manipulating objects in the Mongo datastore – save(), update(), etc. [to do – link to API].
<cfcomponent displayName="MyBlog" extends="cfmongodb.components.MongoDocument">
<cfproperty name="title" />
<cfproperty name="author" />
<cfproperty name="pub_date" />
<cfproperty name="body" />
<cfproperty name="comments" type="array" />
<cfset super.init( collection_name='blog' ) />
<cffunction name="validate">
<!--- Insert custom code which will be executed prior to saves and updates --->
</cffunction>
</cfcomponent>
To create a new MyBlog object and store it in Mongo, create the following client code:
<cfscript>
my_blog = createObject( "component", "MyBlog" );
my_blog.set( 'title', 'My New Blog Title' );
my_blog.set( 'author', 'bill' );
my_blog.set( 'pub_date', now() );
my_blog.set( 'body', 'My brilliant ideas ...' );
my_blog.save();
</cfscript>
<cfscript>
mongo= createObject( 'component', 'cfmongodb.components.MongoDb' );
my_blog = mongo.new_doc( collection_name='blog' );
my_blog.set( 'title', 'My New Blog Title' );
my_blog.set( 'author', 'bill' );
my_blog.set( 'pub_date', now() );
my_blog.set( 'body', 'My brilliant ideas ...' );
my_blog.save();
</cfscript>
The primary difference between the two methods is the way in which documents are created. But both methods perform identical tasks.