You can use upsert() to write one object or a group of objects to the current Cloud DB zone. If an object with the same primary key exists in the Cloud DB zone, the existing object will be updated. Otherwise, a new object will be written. The written data can be obtained from a new object or an object queried from the Cloud DB zone.
When you write a group of objects, the write operation is atomic. That is, all objects in the object list either are successfully written or fail to be written.
Objects to be written in a batch must belong to the same object type. Otherwise, the write operation will fail.
When you write a batch of objects, the total data size must be less than or equal to 2 MB. Otherwise, the write operation will fail.
When you write a batch of objects, the total number of data records must be less than or equal to 1000. Otherwise, the write operation will fail.
When you write a batch of objects, the maximum data length is 200 characters for the string type and 100,000,000 characters for the text type.
When calling the data writing method, there are two ways to return the result: either by returning a Promise object or by passing a callback object in the parameters. The following example explains the Promise approach in detail.
This feature supports phones and tablets by default. Starting from version 5.1.0(18), support for wearables is added. From version 5.1.1(19), TVs are also supported. From version 6.1.0(23), PCs/2-in-1 devices are supported as well.
The Promise object encapsulates the result of the write operation. You can use the Promise object to asynchronously listen for the execution result. If the execution succeeds, you can obtain the number of written objects. Otherwise, you can obtain the error information.
Import required modules.
import { cloudDatabase } from '@kit.CloudFoundationKit';
import { BookInfo } from '../model/BookInfo';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit'; Write the BookInfo object into the Cloud DB zone. If the write operation succeeds, the number of written data records will be returned. Otherwise, an exception will be thrown.
let book = new BookInfo();
book.id = 11;
book.bookName = 'Jane Eyre'
book.price = 100.0;
book.borrowerTime = new Date();
databaseZone.upsert(book).then((record: number) => {
hilog.info(0x0000, 'cloudDb', `Succeeded in upserting: ${record}`);
}).catch((err: BusinessError) => {
hilog.error(0x0000, 'cloudDb', `Failed to upsert, code: ${err.code}, message: ${err.message}`);
});