-
Notifications
You must be signed in to change notification settings - Fork 5
2A. Creating Documents
Populating your entities with data, prior to creating or updating them is as simple as passing a struct in to the populate(document)
method. The populate method checks the passed struct for mapped schema properties and populates those with the values. In other words, you can pass a 'dirty' struct, such as your request context, without concern of poisoning your entity.
Let's populate the person entity:
var person=this.populate({
'first_name'='John',
'last_name'='Doe',
'testvar'='here',
'address'={
'street'='123 Anywhere Lane',
'city'='Grand Rapids',
'state'='Michigan',
'postalcode'='49546',
'country'='USA'
},
'phone'={
'home'='616-123-4567',
'work'='616-321-7654',
'mobile'='616-987-6543'
}
});
Once we've populated the document, we can check to ensure the data meets validation (if it doesn't we can handle our errors - see Validation for more information):
if(person.isValid()){
person.create();
} else {
for(var error in person.getValidationResults().errors){
writeOutput('<p>Validation failed on person because: #error.message#</p>')
}
}
Assigning a variable to person.create()
will provide the key of the document created though, in this case we don't need it. Once we've created the document, it automatically becomes our loaded entity:
var isLoaded=person.loaded(); //will be true
You may retrieve the loaded entity document as a serializable struct by using person.asStruct()
or person.getDocument()
(asStruct()
is a convenience alias to getDocument()
)
The Mongo _id
Key
There is a special 24-bit string _id
value that is created by MongoDB when the document is inserted. This serves as your "primary key" and provides the unique identifier for the document:
var pkey=person.get_id();
Due to MongoDB's clustering and sharding methods, rolling your own _id values (e.g. - auto-incrementing) is strongly discouraged. As such, if you'd like to use your own _id's, you'll need to bypass the Active Entity and use the collection object directly.
For convenience, though, you may add human readable unique values (tags/slugs) and index them:
property name="tag" schema=true index=true unique=true;
If you need to set individual values, you may also use the following methods:
-
set(required string key,required any value)
- the long-form setter method. May be used to handle dot-notated strings -
set[property_name - using underscores instead of dot delimiters](required any value)
- the auto-generated accessor
These saved values may be retrieved using:
-
get[property_name - using underscores instead of dot delimiters]()
- returns the current value of the property -
locate(required string name)
- the public method used to find any key within the nested document schema. Uses dot notation. -
getDocument().propertyName
- retrieves the document struct, which allows for the use of struct notation to traverse it