Saving a single object¶
This is a transaction operation responsible for saving a new object in the database. To add this operation to a Unit Of Work instance, use the following methods:
// custom class approach
unitOfWork.create( object: object );
// untyped objects approach
unitOfWork.create( tableName: string, object: object );
As you can see from the method signatures, there are two approaches for storing a new object in the database: class-based and map-based approaches. The former uses a class defined in your program. The signature defines that class as object
. In this case, the name of the table where the object will be stored is the same as the name of the class. The objectToSave
argument in both signatures must conform the rules defined in the Data Object section of this guide.
Return Value¶
The operation returns an OpResult
object which represents the object stored in the database as a result of this operation. The OpResult
object can be used as an argument in other operations in the same transaction (same UnitOfWork
instance). It is also possible to use OpResult
to "extract" the value of a property of the saved object and use it in other operations. For more information see the Operation Result chapter of this guide.
Example¶
Consider the following example, it demonstrates creating an object and adding it to be saved in a transaction:
const unitOfWork = new Backendless.UnitOfWork();
const person = {
name: "Joe",
age: 25
}
//add OpResult
const addPersonResult = unitOfWork.create( "Person", person );
// add other operations
// ...
// use unitOfWork.execute() to run the transaction
Person class:
function Person(args) {
args = args || {};
this.name = args.name || "";
this.age = args.age || null;
}
const unitOfWork = new Backendless.UnitOfWork();
const person = new Person( {
name: "Joe",
age: 25
});
const addPersonResult = unitOfWork.create(person);
// add other operations
// ...
// use unitOfWork.execute() to run the transaction