Session: How to Check if There are Any Changes on a Session

Single entity can be checked for changes using hasChanged() method, but there is also a possibility to check if there are any changes on a session or even what has changed. Both the hasChanges() method and the whatChanged() method are available in the advanced session operations.

HasChanges

Property indicates if the session contains any changes. If there are any new, changed or deleted entities.

session.advanced.hasChanges();

Example

{
    const session = store.openSession();

    assert.ok(!session.advanced.hasChanges());

    const employee = new Employee();
    employee.firstName = "John";
    employee.lastName = "Doe";

    await session.store(employee);

    assert.ok(session.advanced.hasChanges());
}

WhatChanged

Method returns all changes for each entity stored within the session. Including name of the field/property that changed, its old and new value, and change type.

session.advanced.whatChanged();
ReturnValue
{ [id]: DocumentsChanges[] } Object containing list of changes per document ID.

Example I

{
    const session = store.openSession();

    const employee = new Employee();
    employee.firstName = "John";
    employee.lastName = "Doe";

    await session.store(employee);

    const changes = session.advanced.whatChanged();
    const employeeChanges = changes["employees/1-A"];
    const change =
        employeeChanges[0].change; // "DocumentAdded"

}

Example II

const session = store.openSession();
const employee = await session.load("employees/1-A"); // 'Joe Doe'
employee.firstName = "John";
employee.lastName = "Shmoe";

const changes = session.advanced.whatChanged();
const employeeChanges = changes["employees/1-A"];
const change1 = employeeChanges[0]; // "FieldChanged"
const change2 = employeeChanges[1]; // "FieldChanged"