Creating Documents with SODA for In-Database JavaScript

Creation of documents by SODA for In-Database JavaScript is described.

The SodaDocument class represents SODA documents. Although its focus is on JSON documents, it supports other content types as well. A SodaDocument stores both the actual document’s contents as well as metadata.

JavaScript is especially well-suited to work with JSON by design, giving it an edge over other programming languages.

Here is an example of a simple JSON document:

// Create a JSON document (based on the HR.EMPLOYEES table for employee 100)
const doc = {
    "_id": 100,
    "job_id": "AD_PRES",
    "last_name": "King",
    "first_name": "Steven",
    "email": "SKING",
    "manager_id": null,
    "department_id": 90
};

Note: In SODA, JSON content must conform to RFC 4627.

SodaDocument objects can be created in three ways:

A document has these components:

The document’s content consists of all the fields representing the information the application needs to store plus an _id field. This field is either provided by the user or injected by Oracle if omitted. If omitted, Oracle adds a random value with a length of 12 bytes.

The document’s key is a hex-encoded representation of the document’s _id column. It is automatically calculated and cannot be changed. The key is often used when building operations such as finds, replaces, and removes, with key() and keys(...) methods. These operations are discussed in later sections.

Example: Creating SODA Documents

export function createJSONDoc() {

  // define the document's contents
  const payload = {
    "_id ": 100,
    "job_id": "AD_PRES",
    "last_name": "King",
    "first_name": "Steven",
    "email": "SKING",
    "manager_id": null,
    "department_id": 90
  };

  // Create a SODA document.
  // Notice that neither key nor version are populated. They will be as soon
  // as the document is inserted into a collection and retrieved.
  const doc = soda.createDocument(payload);
  console.log(`
    ------------------------------------------
    SODA Document using default key
    content (select fields):
    - _id          ${doc.getContent()._id}
    - job_id       ${doc.getContent().job_id}
    - first name   ${doc.getContent().first_name}
    media type:    ${doc.mediaType}
    version   :    ${doc.version}
    key            ${doc.key}`
  );
}

Creating SodaDocument instances as shown in this example is the exception rather than the norm. In most cases, developers use SodaCollection.insertOne() or SodaCollection.insertOneAndGet(). The use of SodaCollection.insertOne() is demonstrated in Example: Inserting a SODA Document into a Collection. Multiple documents can be created using sodaCollection.insertMany().