Saving multiple objects¶
This is a transaction operation responsible for saving one or more new objects in the database. To add this operation to a Unit Of Work instance, use the following methods:
// custom class approach
unitOfWork.bulkCreate( objects: object[] );
// untyped objects approach
unitOfWork.bulkCreate( tableName: string, objects: object[] );
The method argument is a collection containing objects which will be stored in the database. As you can see from the method signatures, there are two approaches for storing new objects: 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 objectsToSave
argument in both signatures is a collection of objects to save. Each object must conform to the rules defined in the Data Object section of this guide.
Return Value¶
The operation returns an OpResult
object which represents the result of this operation - a collection of objectId
values. Each element in the resulting collection is a string value. It is the objectId
of the corresponding object stored in the database. 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 example below. In the example three objects are added to a collection. The collection is then added to a transaction with the bulkCreate
method.
const unitOfWork = new Backendless.UnitOfWork();
const people = [
{ name: "Joe", age: 25 },
{ name: "Mary", age: 32 },
{ name: "Bob", age: 22 }
];
unitOfWork.bulkCreate( "Person", people);
// 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 people = [
new Person({ name: "Joe", age: 25 }),
new Person({ name: "Mary", age: 32 }),
new Person({ name: "Bob", age: 22 })
]
unitOfWork.bulkCreate(people);
// add other operations
// ...
// use unitOfWork.execute() to run the transaction