You are currently browsing legacy 4.1 version of documentation. Click here to switch to the newest 4.2 version.

We can help you with migration to the latest RavenDB

Contact Us Now
see on GitHub

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], [callback]); 

  • entity and an id: Stores the entity in a session with given ID.

session.store(entity, id, [callback]);

  • 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], [callback]);
session.store(entity, id, [documentType], [callback]);

All of the above calls accept an optional callback function as the last argument.

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)
callback error-first callback (optional) callback function called when finished
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() it or wait for the callback to be called 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();