Skip to content

CFMongoDB Object Mapper Syntax (proposed)

virtix edited this page Sep 13, 2010 · 35 revisions

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].

Method 1: Extending cfmongodb.components.MongoDocument

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. MongoDocument has methods for storing and manipulating objects from 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" />
        <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>

Method 2: Using the new_doc() factory method


<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.

Clone this wiki locally