Session: Storing Entities

To store entities inside the session object, use store() method.

Syntax

You can pass the following arguments to the store() method:

  • entity only: Stores the entity in the session, then extracts the ID from the entity or generates a new one if it's not available.

session.store(entity, [documentType]);
  • entity and an id: Stores the entity in a session with given ID.

session.store(entity, id);
  • entity, an id and store options: Stores the entity in a session with given ID, forces concurrency check with given change vector.

session.store(entity, id, [options]);
session.store(entity, id, [documentType]);
Parameters
entity object Entity that will be stored
id string Entity will be stored under this ID, (null to generate automatically)
documentType class class used to determine collection of the entity (extracted from entity by default)
options object Options object with the below properties:
changeVector string entity change vector used for concurrency checks (null to skip check)
documentType class class used to determine collection of the entity (extracted from entity by default)
Return value
Promise A promise resolved once entity obtained an ID and is stored in Unit of Work

Asynchronous call

store() method is asynchronous (since it reaches out to server to get a new ID) and returns a Promise, so don't forget to use either await, .then() before saving changes.

On collection name when storing object literals

In order to comfortably use object literals as entities set the function getting collection name based on the content of the object - store.conventions.findCollectionNameForObjectLiteral()

const store = new DocumentStore(urls, database);
store.conventions.findCollectionNameForObjectLiteral = entity => entity["collection"];
// ...
store.initialize();

This needs to be done before an initialize() call on DocumentStore instance. If you fail to do so, your entites will land up in @empty collection having an UUID for an ID.

Example

const employee = new Employee("John", "Doe");

// generate Id automatically
await session.store(employee);

// send all pending operations to server, in this case only `Put` operation
await session.saveChanges();