Create, Update, and Delete Data from a Database Using JavaScript
When you transform a Type into what is called an Entity Type (also known as Persistable), you gain the ability to persist data in a database, which you can then retrieve at a later time.
This topic explains how to create, update, and delete data from the database using the JavaScript SDK. There is also a version of this document that uses the Python SDK version instead of JavaScript.
Data modeling
For this tutorial, assume you have defined a new type that allows keeping track of information about smart bulbs like their wattage and lumens:
entity type SmartBulb schema name "SMRT_BLB" {
bulbType: !string enum('LED', 'INCAN', 'CFL')
manufacturer: string
wattage: decimal
lumens: decimal
startDate: !datetime
}The bulbType and startDate are required fields.
Create an in-memory instance
To create an in-memory instance without persisting the type in the database, call the .make() method on the type:
var bulb = SmartBulb.make({
bulbType: "LED",
manufacturer: "Philips",
startDate: "2024-01-07"
});Create and persist data in the database
Use the Persistable#create method to create a new instance and persist it in the database:
var bulb = SmartBulb.make({
bulbType: "LED",
manufacturer: "Philips",
startDate: "2024-01-07"
}).create();When you call the .create() method, two processes occur. The first is that if you do not provide a unique ID, one is automatically created for you:
// Create smart bulb with a specific ID
var bulb = SmartBulb.make({
id: "jW2dGw",
bulbType: "LED",
manufacturer: "Philips",
startDate: "2024-01-07"
}).create();
// Or, let .create() generate a unique ID
var bulb = SmartBulb.make({
bulbType: "LED",
manufacturer: "Philips",
startDate: "2024-01-07"
}).create();
// C3.typesys.Obj {id: '4e0405a9-7a93-4a79-bb6e-fdda0f9a5365', meta: {…}, version: 1, versionEdits: ImmutableArray(0)…}The second thing to happen is that .create() automatically validates your data to make sure it complies with your Type definition. In this example, the bulbType attribute is mandatory and only accepts a set of valid values.
If you try to create a smart bulb without that field, or with a string that's different from the ones allowed, you get an error:
try {
SmartBulb.make({}).create();
} catch(err) {
console.log(err);
}
// Write failed: Required field SmartBulb.bulbType not set.Finally, the .create() method also supports customization. By default, the method returns all fields that are not null; however, you can customize that behavior by specifying an UpsertSpec object:
var bulb = SmartBulb.make({
bulbType: "LED",
manufacturer: "Philips",
startDate: "2024-01-07"
}).create({
returnInclude: "id"
});
bulb.id
// "65ae9a9e-6827-4f8b-9d7f-bf88983b684a"
bulb.manufacturer
// undefinedUpdate data in the database
After you have created an instance in the database, you can update it with Persistable#update.
var bulb = SmartBulb.make({
bulbType: "LED",
manufacturer: "Philips",
startDate: "2024-01-07"
}).create({
returnInclude: "id, startDate"
});
// Update the bulbType property with a different string
bulb = bulb.withBulbType("CFL");
// Update the database with the latest values
bulb = bulb.update();
// Retrieve the latest data from the Database
bulb.get();If the instance does not exist yet in the database, an error is returned.
The withBulbType() API is generated automatically for all fields on a Type. For example, this could be withId(), withManufacturer(), etc. There is a without API (e.g. withoutBulbType()) generated automatically as well. You should not attempt to directly set a Type instance properties like this:
// INCORRECT SYNTAX - WILL NOT WORK
bulb.bulbType = 'CFL'The above command will not throw an error, but it will not actually update the property on the instance.
Create or update data in the database
While .update() throws an error if the instance does not exist yet in the database, sometimes it is useful to create a new instance in the database if one does not exist yet. Use Persistable#upsert to achieve this:
// In-memory instance, doesn't exist in the database yet
var bulb = SmartBulb.make({
bulbType: "LED",
manufacturer: "Philips",
startDate: "2024-01-07"
})
// We're not specifying an ID, so a unique one is generated. Since there is not a smart bulb record with that ID in the
// database yet, this one is inserted
bulb = bulb.upsert();
// Retrieve the latest data from the Database
bulb = bulb.get();
// Update the bulbType property with a different string
bulb = bulb.withBulbType("CFL");
// Set the manufacturer property to null
bulb = bulb.withoutManufacturer();
// Upsert again, but this time a smart bulb with this ID already exists, so we update it with the latest values
bulb = bulb.upsert();
// Retrieve the latest data from the Database
bulb.get();.update() updates the database with the latest value for all attributes of the instance. If some of those attributes are set with a null value, the database is updated with null.
upsert creates an instance of a C3 type if it does not exist or updates it if it does.
After making updates you can view the content of the SmartBulb in a table by calling fetch on the SmartBulb:
c3Grid(SmartBulb.fetch());The result of calling fetch will display a grid of data in the static console.
Update only specific attributes with merge
Sometimes you want to persist in the databases changes to attributes only if the attribute was set with a value, and not persist any changes to attributes that are not defined or are set to null.
You can use Persistable#merge to achieve this. See the following example code snippet.
var bulbWithType = SmartBulb.make({id: '2x3fMq', bulbType: "LED", startDate: "2024-01-07"});
var bulbWithManufacturer = SmartBulb.make({id: '2x3fMq', manufacturer: "Philips"});
// Persist bulb 2x3fMq in the database
bulbWithType = bulbWithType.create();
// Create bulb 2x3fMq if it doesn't exist yet, or update it to have information about the manufacturer.
bulbWithAllAttributes = bulbWithManufacturer.merge();
// Retrieve the latest data from the Database.
// This can also be accomplished with bulbWithAllAttributes.get()
SmartBulb.forId('2x3fMq').get()Delete data from the database
Use the Persistable#remove method to delete instances from the database:
// Create new smart bulb and insert it into the database
var bulb = SmartBulb.make({
id: 'YrmW5p',
bulbType: "LED",
startDate: "2024-01-07"
}).create();
// Remove smart bulb YrmW5p from the database
bulb.remove();Create, update, and delete batches of data
All data manipulation methods have a batch counterpart, so you can operate on multiple instances at the same time:
// The data for multiple smart bulbs
var bulbs = [
{id: "gerXzN", bulbType: "LED", manufacturer: "Philips", startDate: "2024-01-07"},
{id: "QtY2b1", bulbType: "LED", manufacturer: "GE", startDate: "2024-04-07"},
{id: "3P6kEf", bulbType: "LED", manufacturer: "Sylvania", startDate: "2024-03-07"}
];
// Insert multiple smart bulbs in batch in the database
SmartBulb.createBatch(bulbs);
// Removes multiple instances of a C3 type from the database
// `removeBatch` will remove all objects passed into the removeBatch function
SmartBulb.removeBatch(bulbs);| Type containing functions for create operations | Description |
|---|---|
| Persistable#create | Creates an instance of a Type. This will fail if the instance already exist. If the operation fails an exception will be thrown. Use create when you are creating a new instance of the Type. |
| Persistable#upsert | Creates an instance of a Type if it doesn't exist or updates it if it does. If the operation fails an exception will be thrown. |
| Persistable#update | Updates an instance of a Type. This will fail if the instance does not already exist. If the operation fails an exception will be thrown. |